leetcode 90. 子集 II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
思路和上一题类似,这里在最后把多余的排列除去即可,在有重复元素的nums中,要对其排序,再进行,处理,否则会出错
 1 #include<algorithm>
 2 class Solution {
 3 public:
 4     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
 5         vector<vector<int>> ans(1);
 6         sort(nums.begin(), nums.end());
 7         for(int i = 0; i < nums.size(); i++){
 8             int len = ans.size();
 9             for(int j = 0; j < len; j++){
10                 ans.push_back(ans[j]);
11                 ans.back().push_back(nums[i]);
12             }
13         }
14         sort(ans.begin(), ans.end());
15         ans.erase(unique(ans.begin(), ans.end()), ans.end());
16         return ans;
17     }
18 };

递归算法:

 1 #include<algorithm>
 2 class Solution {
 3 public:
 4     void dfs(vector<int> nums, vector<int>& temp, vector<vector<int>>& ans, int begin){
 5         ans.push_back(temp);
 6         for(int i = begin; i < nums.size(); i++){
 7             if(i==begin||nums[i]!=nums[i-1]){//dfs中常有这种结构,先添加,在递归,最后再复原
 8                 temp.push_back(nums[i]);
 9                 dfs(nums, temp, ans, i+1);
10                 temp.pop_back();
11             }
12         }
13     }
14     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
15         vector<vector<int>> ans;
16         vector<int> temp;
17         sort(nums.begin(), nums.end());
18         dfs(nums, temp, ans, 0);
19         return ans;
20     }
21 };

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/8997775.html