1. 程式人生 > >leetcode 90. 子集 II

leetcode 90. 子集 II

思路 給定 ans dfs bsp 處理 gin == oid

給定一個可能包含重復元素的整數數組 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 };

leetcode 90. 子集 II