【ATT】subsets II

Q:

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

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

A: DFS问题。注意集合S中有重复。

   vector<vector<int> > subsetsWithDup(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> path;
        vector<vector<int> > result;
        sort(S.begin(),S.end());
        sub(S,0,path,result);
        return result;
    }
    
    void sub(vector<int>& S, int curPos,vector<int>& path,vector<vector<int> >& result)
    {
        result.push_back(path);
        for(int i=curPos;i<S.size();i++)
        {
           if(i!=curPos&&S[i]==S[i-1])   //跳过重复的
             continue;
           path.push_back(S[i]);
           sub(S,i+1,path,result);
           path.pop_back();
        }
        
    }

  

posted @ 2013-08-08 23:49  summer_zhou  阅读(180)  评论(0编辑  收藏  举报