[LeetCode] Subsets II

Subsets II

Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解题思路:

去重的话用一个set来记录。枚举的话,可以二进制递增来枚举。i从0递增到2^n-1,若i的二进制表示中,相应位为1,则添加到项中。

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> result;
        set<vector<int>> contains;  //已经包含的
        std::sort(nums.begin(), nums.end());
        
        int num = 1 << nums.size();
        for(int i=0; i<num; i++){
            int flag = i;
            int j=0;
            vector<int> item;
            while(flag!=0){
                if(flag&0x1==1){
                    item.push_back(nums[j]);
                }
                flag = flag>>1;
                j++;
            }
            if(contains.find(item)==contains.end()){
                contains.insert(item);
                result.push_back(item);
            }
        }
        
        
        return result;
    }
};


转载请注明:康瑞部落 » [LeetCode] Subsets II

0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注