subsets-ii

【题目描述】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],
[]
]
给定一个数组(数组内元素可能有重复),求其所有的子集。(但是子集之间不能重复)

【解题思路】先对数组排序,深度遍历,遇到相同的跳过

【考查内容】数组

class Solution {
private:
    vector<vector<int> > result;
    vector<int> tmp;
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        sort(S.begin(),S.end());
        dfs(S,0);
        return result;
    }
    void dfs(vector<int> set, int start){
        result.push_back(tmp);
        for(int i = start; i < set.size(); ++ i){
            tmp.push_back(set[i]);
            dfs(set,i+1);
            while(i<set.size()-1 && set[i+1]==set[i]) ++i;//比subset1多出的一行
            tmp.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36909758/article/details/90765273