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

LeetCode90 Subsets II

时间:2016-10-22 00:15:59      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:复杂   dup   leetcode   amp   添加   example   res   tco   bsp   

题目:

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets. (Medium)

For example,
If nums = [1,2,2], a solution is:

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

分析:

这次相较于subsetsI有了重复元素,所以一个简单的思路就是判重,重复的不添加到结果中(但时间复杂度稍高,不过既然是回溯,也就不太在乎时间复杂度了)

代码:

 1 class Solution {
 2 private:
 3     void helper(vector<int>& nums, vector<int>& temp, int start, vector<vector<int>>& result) {
 4         if (start == nums.size()) {
 5             return;
 6         }
 7         temp.push_back(nums[start]);
 8         vector<int> input = temp;
 9         sort(input.begin(), input.end());
10         if (find(result.begin(), result.end(), input) == result.end()) {
11             result.push_back(input);
12         }
13         helper(nums, temp, start + 1, result);
14         temp.pop_back();
15         helper(nums, temp, start + 1, result);
16     }
17 public:
18     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
19         vector<vector<int>> result;
20         vector<int> temp;
21         result.push_back(temp);
22         helper(nums, temp, 0, result);
23         return result;
24     }
25 };

 

LeetCode90 Subsets II

标签:复杂   dup   leetcode   amp   添加   example   res   tco   bsp   

原文地址:http://www.cnblogs.com/wangxiaobao/p/5986212.html

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