首页 > 其他 > 详细

[LeetCode] Subsets II

时间:2018-01-25 23:42:36      阅读:234      评论:0      收藏:0      [点我收藏+]
 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

原文:https://www.cnblogs.com/immjc/p/8353581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!