Subsets,Subsets II

时间:2021-12-07 15:26:57

一.Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
class Solution {
public:
void dfs(vector<int>& nums ,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
{
for(int i=startPos;i<numsSize;i++){
oneOfRes.push_back(nums[i]);
res.push_back(oneOfRes);
dfs(nums,numsSize,i+,res,oneOfRes);
oneOfRes.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
vector<int> oneOfRes;
res.push_back(vector<int>());
int numsSize = nums.size();
dfs(nums,numsSize,,res,oneOfRes);
return res;
}
};

二.SubsetsII

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
class Solution {
public:
void dfs(vector<int>& nums,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
{
for(int i=startPos;i<numsSize;i++){
if(i>startPos && nums[i]==nums[i-]){
continue;
}
oneOfRes.push_back(nums[i]);
res.push_back(oneOfRes);
dfs(nums,numsSize,i+,res,oneOfRes);
oneOfRes.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
vector<int> oneOfRes;
int numsSize = nums.size();
res.push_back(oneOfRes);
dfs(nums,numsSize,,res,oneOfRes);
return res;
}
};