18. Subsets II【medium】
Given a list of numbers that may has duplicate numbers, return all possible subsets
Notice
- Each element in a subset must be in non-descending order.
- The ordering between two subsets is free.
- The solution set must not contain duplicate subsets.
Example
If S = [1,2,2]
, a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Challenge
Can you do it in both recursively and iteratively?
题意
给定一个可能具有重复数字的列表,返回其所有可能的子集
注意事项
- 子集中的每个元素都是非降序的
- 两个子集间的顺序是无关紧要的
- 解集中不能包含重复子集
解法一:
1 class Solution { 2 public: 3 /* 4 * @param nums: A set of numbers. 5 * @return: A list of lists. All valid subsets. 6 */ 7 vector<vector<int>> subsetsWithDup(vector<int> &nums) { 8 // write your code here 9 vector<vector<int> > results; 10 vector<int> result; 11 12 sort(nums.begin(), nums.end()); 13 14 helper(nums, 0, result, results); 15 16 return results; 17 } 18 19 void helper(vector<int> &nums, int start, vector<int> & result, vector<vector<int> > & results) 20 { 21 results.push_back(result); 22 23 for (int i = start; i < nums.size(); ++i) { 24 if (i > start && nums[i] == nums[i - 1]) { 25 continue; 26 } 27 28 result.push_back(nums[i]); 29 30 helper(nums, i + 1, result, results); 31 32 result.pop_back(); 33 } 34 } 35 };
posted on 2018-01-20 12:02 LastBattle 阅读(120) 评论(0) 编辑 收藏 举报