您的位置:首页 > 其它

[LeetCode]Subsets II

2014-03-24 19:49 405 查看
原题链接: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],
[]
]

题解:

  这题是含重复元素的子集生成,简化版本是集合中无重复元素,见http://www.cnblogs.com/codershell/p/3619928.html,

  我在《子集问题(寻找给定集合的所有子集)》一文中详细分析了子集问题,具体解释不再赘述。

class Solution {
public:
bool isExist(vector<vector<int> > &vv,vector<int> v){
for(int i=0; i<vv.size(); i++)
if(vv[i] == v)
return true;

return false;
}

void ss(vector<vector<int> > &vv,int* flag,int n, vector<int> &S, int cur){
if(cur == n){
vector<int> v;
for(int i = 0; i < cur; i++)
if(flag[i])
v.push_back(S[i]);
if(!isExist(vv,v))
vv.push_back(v);
return;
}

flag[cur] = 1;                                // 选第 cur 个元素
ss(vv,flag,n, S, cur+1);
flag[cur] = 0;                                // 不选第 cur 个元素
ss(vv,flag,n, S, cur+1);
}

vector<vector<int> > subsetsWithDup(vector<int> &S) {
int *flag = (int *)malloc(sizeof(int) * S.size()) ;

vector <vector<int>> array;
sort(S.begin(),S.end());
ss(array,flag,S.size(),S,0);
free(flag);
return array;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: