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

思路:

 这题采用的动态规划,通过分析S[i]在子集和不在子集两种情况来求解。
1.刚开始,我们可以加入S[0],此时为{},{1}   即为当S为1时,s[0]在子集中和不在子集中两种情况
2.再加入s[1],此时,{},{1},{2},{1,2}   即为当S为12时,s[1]在子集中和不在子集中两种情况
3.依次扩充S,即可。

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> >res;
        if(S.size()<=0) return res;
        sort(S.begin(),S.end());
        for(int i=0;i<S.size();++i)
        {
            if(res.empty())
            {
                vector<int>temp;
                res.push_back(temp);
                temp.push_back(S[0]);
                res.push_back(temp);
                continue;
            }
            else
            {
                int size=res.size();
                for(int j=0;j<size;++j)
                {
                    vector<int>vec(res[j]);
                    vec.push_back(S[i]);
                    res.push_back(vec);
                }
            }
        }
        set<vector<int> >Set(res.begin(),res.end());
        vector<vector<int> >ans(Set.begin(),Set.end());
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/90775926
今日推荐