LeetCode算法系列:90.Subsets
阿新 • • 發佈:2018-12-14
題目描述:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
演算法實現:
和78.Subsets非常類似,只不過對於重複的元素的處理要繁瑣一點,對於重複n次的元素,在子群中可能0,1,2,3...n次;
另外如果沒有重複元素原陣列沒有必要進行排序,對於有重複元素的陣列要對重複元素進行單獨處理,因此有必要對陣列進行排序
class Solution { public: vector<vector<int>> res; vector<int> oneres; void recursive(vector<int>& nums, int n){ if(n == 0){ res.push_back(oneres); } else{ int i = 1; while(n - 1 - i >= 0 && nums[n - 1 - i] == nums[n - 1])i ++; recursive(nums, n - i); for(int k = 1; k <= i; k ++){ for(int j = 0; j < k; j ++)oneres.push_back(nums[n - 1]); recursive(nums, n - i); for(int j = 0; j < k; j ++)oneres.pop_back(); } } } vector<vector<int>> subsetsWithDup(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); recursive(nums, n); return res; } };