地址:http://oj.leetcode.com/problems/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], [] ]思路:dfs+回溯。关于如何去重,有几种方式,笔者这种是比较耗费时间的,可以用条件判断是否继续dfs来去重。这个还要研究一下,因为更节约时间。AC耗时136ms
参考代码:
class Solution {
public:
void dfs(vector<vector<int>>&ans, vector<int>&S, vector<bool>&visited, vector<int>vec, int st)
{
if(st == S.size())
{
if(find(ans.begin(), ans.end(), vec)==ans.end())
ans.push_back(vec);
return;
}
dfs(ans, S, visited, vec, st+1);
if(visited[st])
return;
vec.push_back(S[st]);
visited[st] = true;
dfs(ans, S, visited, vec, st+1);
visited[st] = false;
vec.pop_back();
}
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>>ans;
if(S.empty())
return ans;
sort(S.begin(), S.end());
vector<int>vec;
vector<bool>visited(S.size(), false);
dfs(ans, S, visited, vec, 0);
return ans;
}
};