LeetCode No.90 Subsets II

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

===================================================================

題目鏈接:https://leetcode.com/problems/subsets-ii/

題目大意:求出nums的所有子集,不能包含重複子集。

思路:dfs,先對nums進行排序,參數多加一個記錄index表示當前可以dfs的下標,爲了除重。

參考代碼:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector < vector <int> > ans ;
        vector <int> ret ;
        sort ( nums.begin() , nums.end() ) ;
        dfs ( nums , ret , 0 , ans ) ;
        return ans ;
    }
private :
    void dfs ( vector <int>& nums , vector <int> ret , int index , vector < vector <int> >& ans )
    {
        ans.push_back ( ret ) ;
        if ( index >= nums.size() )
            return ;
        for ( int i = index ; i < nums.size() ; i ++ )
        {
            vector <int> temp = ret ;
            temp.push_back ( nums[i] ) ;
            dfs ( nums , temp , i + 1 , ans ) ;
            while ( i + 1 < nums.size() && nums[i+1] == nums[i] )//除重
                i ++ ;
        }
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章