1. 程式人生 > >【LeetCode】Subsets II

【LeetCode】Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

題解:給出所有子集,先排序然後統計每個數出現次數,之後遍歷當前子集,對每個子集一個一個的加入這個數

程式碼:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        
        vector<vector<int>> ans={{}};
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();){
           int cnt=0;
            while(i+cnt<nums.size()&&nums[i]==nums[i+cnt]){
                cnt++;
            }
            int N=ans.size();
            for(int k=0;k<N;k++){
                vector<int> tmp=ans[k];
                for(int j=0;j<cnt;j++){
                    tmp.push_back(nums[i]);
                    ans.push_back(tmp);
                }
            }
            i+=cnt;
        }
        return ans;
    }
};