码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Subsets II

时间:2018-01-26 00:35:32      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:post   body   end   pow   oid   不能   重复   子集   blog   

 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

标签:post   body   end   pow   oid   不能   重复   子集   blog   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!