18. Subsets II【medium】
阿新 • • 發佈:2018-01-20
sort 元素 help hat oss numbers ack star order
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.
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 };
18. Subsets II【medium】