Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Solution: Iterative
- We don't need to sort the input array
- We can push an empty vector to the result vector first
- Iterate through the input vector
- Append the number to all subsets in vector and push it back to result vector
- We need to remember the size of the current vector first
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans(1, vector<int>());
for (int i=0; i<nums.size(); i++) {
int n = ans.size();
for (int j=0; j<n; j++) {
ans.push_back(ans[j]);
ans.back().push_back(nums[i]);
}
}
return ans;
}
Solution: Backtracking
- First we need to sort the input arry
vector<vector<int>> subsets(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> subs;
vector<int> sub;
genSubsets(nums, 0, sub, subs);
return subs;
}
void genSubsets(vector<int>& nums, int start, vector<int>& sub, vector<vector<int>>& subs) {
subs.push_back(sub);
for (int i = start; i < nums.size(); i++) {
sub.push_back(nums[i]);
genSubsets(nums, i + 1, sub, subs);
sub.pop_back();
}
}