90. Subsets II

2017-01-05  本文已影响0人  juexin

Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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], [] ]

class Solution {
public:
    void dfs(vector<int> &nums,vector<vector<int>> &result,int step,vector<int> &tmp)
    {
        
        result.push_back(tmp);//不需要所有的数字都参与
        
        //如果需要所有的数字都参与
        /*if(step == nums.size()) 
        {
            result.push_back(tmp);
            return;
        }*/
        
        for(int i=step;i<nums.size();i++)
        {   if(i!=step&&nums[i]==nums[i-1])
               continue;
            tmp.push_back(nums[i]);
            dfs(nums,result,i+1,tmp); //到底什么情况是dfs(nums,result,i+1,tmp),什么情况是dfs(nums,result,step+1,tmp),需要仔细分析
            tmp.pop_back();
        }
    }
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
         vector<vector<int>> result;
        if(nums.size()<=0)
           return result;
        vector<int> tmp;
        sort(nums.begin(),nums.end());
        dfs(nums,result,0,tmp);
        return result;
    }
};
上一篇下一篇

猜你喜欢

热点阅读