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], [] ]
Pick a starting point.
while(Problem is not solved)
For each path from the starting point.
check if selected path is safe, if yes select it
and make recursive call to rest of the problem
before which undo the current move.
End For
If none of the move works out, return false, NO SOLUTON.
class Solution {
private:
vector<vector<int> > ans;
public:
void sub(vector<int> &nums,int i,vector<int>& res)
{
ans.push_back(res);
for(int j=i;j<nums.size();++j)
{ res.push_back(nums[j]);
sub(nums,j+1,res);
res.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> v;
sub(nums,0,v);
return ans;
}
};
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> subs = {{}};
for (int num : nums) {
int n = subs.size();
for (int i = 0; i < n; i++) {
subs.push_back(subs[i]);
subs.back().push_back(num);
}
}
return subs;
}
};
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int n = nums.size(), p = 1 << n;
vector<vector<int>> subs(p);
for (int i = 0; i < p; i++) {
for (int j = 0; j < n; j++) {
if ((i >> j) & 1) {
subs[i].push_back(nums[j]);
}
}
}
return subs;
}
};