Subsets II
Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2]
, a solution
is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
算法思想:
递归求解,按照答案要求先要排序
class Solution { public: void dfs(vector<int> &S,int start,vector<int> &path,vector<vector<int>> &result){ result.push_back(path); for(int i=start;i<S.size();i++){ if(i!=start&&S[i]==S[i-1])continue; path.push_back(S[i]); dfs(S,i+1,path,result); path.pop_back(); } } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> result; vector<int> path; sort(S.begin(),S.end()); dfs(S,0,path,result); return result; } };