首页 > 代码库 > LeetCode90 Subsets II
LeetCode90 Subsets II
题目:
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。