https://oj.leetcode.com/problems/subsets-ii/
求一个集合的子集,但集合中有重复元素。
求子集的问题,对应着数的二进制,相当于对二进制的一个遍历。
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int> > ans; if(S.size()==0) return ans; int num = pow(2,S.size()); sort(S.begin(),S.end()); for(int i = 0; i<num; i++) { vector<int> ansPiece; ansPiece = oneSubsetPiece(i,S); bool flag = 1; for(int j = 1; j<ans.size(); j++) { if(ansPiece == ans[j]) flag = 0; } if(flag == 1) ans.push_back(ansPiece); } return ans; } //find the num's binary vector<int> oneSubsetPiece(int num,vector<int> &S) { vector<int> ansPiece; int YuShu; int ChuShu; int index = 0; while(num) { YuShu = num %2; num = num/2; if(YuShu) ansPiece.push_back(S[index]); index++; } return ansPiece; } }; int main() { class Solution sol; vector<int> num; num.push_back(1); num.push_back(2); num.push_back(2); sol.subsetsWithDup(num); }