78. 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],[]]
class Solution {
public:
void backtrack(vector<int>& nums,vector<vector<int>>& vv,vector<int>& v,int num)
{
if(num==nums.size())
{
vv.push_back(v);
return;
}
v.push_back(nums[num]);
backtrack(nums,vv,v,num+1);
v.pop_back();
backtrack(nums,vv,v,num+1);
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> v;
vector<vector<int>> vv;
backtrack(nums,vv,v,0);
return vv;
}
};
90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[[2],[1],[1,2,2],[2,2],[1,2],[]]
class Solution {
public:
void backtrack(vector<int>& nums,vector<vector<int>>& vv,vector<int>& v,int num,int flag,int on)
{
if(num==nums.size())
{
vv.push_back(v);
return;
}
if(on==0&&flag==1)
{
on=1;
if(num<nums.size()-1)
{
if(nums[num]==nums[num+1])
flag=1;
else
flag=0;
}
backtrack(nums,vv,v,num+1,flag,0);
}
else
{
if(num<nums.size()-1)
{
if(nums[num]==nums[num+1])
flag=1;
else
flag=0;
}
v.push_back(nums[num]);
backtrack(nums,vv,v,num+1,flag,1);
v.pop_back();
backtrack(nums,vv,v,num+1,flag,0);
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> v;
vector<vector<int>> vv;
backtrack(nums,vv,v,0,-1,1);
return vv;
}
};