Subsets II

来源:互联网 发布:淘宝游戏充值赚钱吗 编辑:程序博客网 时间:2024/05/29 16:26

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],  []]
这道题例子和题目的non-descending有些出入。。DFS的一题

代码如下:

class Solution {private:    vector<vector<int> > result;    vector<int> temp;public:    vector<vector<int> > subsetsWithDup(vector<int> &S) {        temp={};        result.clear();        result.push_back(temp);                int len  = S.size();        if(len==0) return result;        sort(S.begin(),S.end());//greater<int>()        bool used[len];        memset(used,false,sizeof(bool)*len);                solve(S,used,0,0);                return result;    }        void solve(vector<int> &S,bool *used,int start,int dep)    {        if(dep == S.size()||start>S.size())            return;        for(int i = start;i <S.size();i++)        {            if(i>start&&S[i-1]==S[i]&&!used[i-1])                continue;            used[i] = true;            temp.push_back(S[i]);            result.push_back(temp);            solve(S,used,i+1,dep+1);            temp.pop_back();            used[i] = false;        }    }};

我这里是用了一个数组used来解决有重复数字的问题。大致方法就是

在同一深度dep上,如果两个数相同,而之前那个数没有使用过,那么后面那个数就不能使用。

其实后来想想,只需要保证,在同一深度上,有相同的数字,那么我们只使用第一个,其他后面的都continue。就完全不需要used数组来进行记录了


0 0
原创粉丝点击