https://leetcode.com/problems/subsets-ii/
暴力方法就是用Set了 当然时间复杂度也上来了
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int>& nums) {
vector < vector<int> > ret;
vector<int> tmp;
sort (nums.begin() , nums.end() );
if( nums.size()==0 )
return ret;
dfs(ret, 0, tmp, nums);
return ret;
}
void dfs( vector < vector <int> > &ret, int ptr, vector <int> tmp, vector<int> &nums) {
if( ptr >= nums.size() ) {
if( ret.size()==0 ||
ret[ ret.size()-1 ] != tmp )
ret.push_back( tmp );
return ;
}
dfs(ret, ptr+1, tmp, nums);
tmp.push_back( nums[ptr] );
dfs(ret, ptr+1, tmp, nums);
}
};
看到discuss的方法:
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> tmp;
backtracking(res, tmp, nums, 0);
return res;
}
void backtracking(vector<vector<int>>& res, vector<int> tmp, vector<int>& nums, int begin){
res.push_back(tmp);
for(int i = begin; i < nums.size(); i++){
if(i == begin || nums[i] != nums[i - 1]){
tmp.push_back(nums[i]);
backtracking(res, tmp, nums, i + 1);
tmp.pop_back();
}
}
}
};
模拟一下1 1 2 2 2