[leetcode] 90. Subsets II 解题报告

题目链接: https://leetcode.com/problems/subsets-ii/

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

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

思路: 还是一个DFS, leetcode有很多类似的重复变形的题目, 和不包含重复元素的区别是在遍历到某个值时, 可以分为拿和不拿. 如果拿的话就按照正常往下一层搜索, 如果不拿当前值的话, 那么也要跳过接下来和当前值相等的元素.

代码如下:

class Solution {
public:
    void DFS(vector<int>& nums, vector<int> vec, int k)
    {
        if(k >= nums.size()) return result.push_back(vec);
        int x = k;
        while(k+1 < nums.size() && nums[k] == nums[k+1]) k++;
        DFS(nums, vec, k+1);
        vec.push_back(nums[x]);
        DFS(nums, vec, x+1);
    }
    
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        if(nums.size()==0) return {};
        sort(nums.begin(), nums.end());
        DFS(nums, vector<int>(), 0);
        return result;
    }
private:
    vector<vector<int>> result;
};

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/qq508618087/article/details/49528235
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞