[LeetCode] Subsets II

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Subsets II相关的知识,希望对你有一定的参考价值。

 Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

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

使用回溯法求解,要求结果不能包含重复的子集。

所以先对给定数组排序后利用find函数去重。

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> tmp;
        int idx = 0;
        sort(nums.begin(), nums.end());
        helper(res, tmp, nums, idx);
        return res;
    }
    
    void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int idx) {
        if (find(res.begin(), res.end(), tmp) == res.end())
            res.push_back(tmp);
        for (int i = idx; i < nums.size(); i++) {
            tmp.push_back(nums[i]);
            helper(res, tmp, nums, i + 1);
            tmp.pop_back();
        }
    }
};
// 12 ms

 


以上是关于[LeetCode] Subsets II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 90:Subsets II

LeetCode OJ 090Subsets II

LeetCode OJ 090Subsets II

[LeetCode] 90. Subsets II 子集合 II

Leetcode 90. Subsets II

LeetCode:Subsets II