Subsets II (leetcode)

来源:互联网 发布:iphone照片备份软件 编辑:程序博客网 时间:2024/06/06 09:48

题目:

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],  []]

方法:把vector中的数不断取出来,然后加一位再添到最后。

代码:

#include<iostream>#include<vector>#include<algorithm>using namespace std;vector<vector<int> > subsetsWithDup(vector<int> &S){vector<vector<int> > results;if(S.empty())return results;sort(S.begin(),S.end());for(int i=0;i<S.size();i++){int size=results.size();for(int j=0;j<size;j++){vector<int> result=results[j];result.push_back(S[i]);results.push_back(result);}results.push_back(vector<int> (1,S[i]));}sort(results.begin(),results.end());results.erase(unique(results.begin(),results.end()),results.end());results.push_back(vector<int>(0));return results;}int main(){vector<int> S(3);S[0]=0;S[1]=2;S[2]=3;vector<vector<int> > results=subsetsWithDup(S);system("pause");return 0;}

0 0
原创粉丝点击