78. Subsets
题目链接:https://leetcode.com/problems/subsets/
题目描述:
Given a set of distinct integers, nums, return all possible subsets.
Note: 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:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> re;
vector<int> tmp;
re.push_back(tmp);
dfs(0,tmp,re,nums);
return re;
}
void dfs(int start,vector<int>& tmp,vector<vector<int>>& re,vector<int>& nums){
for(int i=start;i<nums.size();i++){
tmp.push_back(nums[i]);
re.push_back(tmp);
dfs(i+1,tmp,re,nums);
tmp.pop_back();
}
}
};
90. Subsets II
题目链接:https://leetcode.com/problems/subsets-ii/
题目描述:
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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], [] ]思路1:仿照binary watch那道题的思路,先深入到最底部,然后回溯,判断、存储,对于这道题来说有些麻烦,最后提交很慢
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> re;
vector<int> tmp;
sort(nums.begin(),nums.end());
for(int i=0;i<=nums.size();i++)
{
dfs(0,i,nums,tmp,re);
}
sort(re.begin(),re.end());
re.erase(unique(re.begin(),re.end()),re.end());
return re;
}
void dfs(int curIndex,int k,vector<int> nums,vector<int> tmp,vector<vector<int>>& re)
{
if(k==0) re.push_back(tmp);
if(curIndex==nums.size()||k==0) return;
dfs(curIndex+1,k,nums,tmp,re);
tmp.push_back(nums[curIndex]);
curIndex++;k--;
dfs(curIndex,k,nums,tmp,re);
}
};
思路2:借鉴dr的思路,(可以画一棵树看看),边深入边存储路径,回溯、存储路径,提交快很多
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> re;
vector<int> tmp;
re.push_back(tmp);
sort(nums.begin(),nums.end());
dfs(0,nums,tmp,re);
return re;
}
void dfs(int start,vector<int> nums,vector<int>& tmp,vector<vector<int>>& re)
{
for(int i=start;i<nums.size();i++)
{
if(i>start&&nums[i]==nums[i-1]) continue;
tmp.push_back(nums[i]);
re.push_back(tmp);
dfs(i+1,nums,tmp,re);
tmp.pop_back();
}
}
};