leetcode 90. Subset II

Given an integer array  nums that may contain repeated elements , return all possible subsets (power sets) of the array.

Explanation: The solution set cannot contain duplicate subsets.

Example:

Input: [1,2,2]
output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
] 
The idea is similar to the previous question. Here, the redundant arrangement can be removed at the end. In the nums with repeated elements, they must be sorted, and then processed, otherwise an error will occur.
 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                  years.push_back(years[j]);
11                  years.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 years;
17      }
 18 };

Recursive algorithm:

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 ]){//This is often found in dfs This structure is added first, recursively, and finally restored
 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 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339289&siteId=291194637