#Leetcode# 90. Subsets II
阿新 • • 發佈:2018-11-25
https://leetcode.com/problems/subsets-ii/
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], [] ]
題解:$nums$ 要排序
程式碼:
class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { int n = nums.size(); set<vector<int>> ans; vector<int> v; vector<int> cnt; sort(nums.begin(), nums.end()); for(int i = 0; i < (1 << n); i ++) { v.clear(); cnt.clear(); A(v, i); for(int j = 0; j < v.size(); j ++) if(v[j] == 1) cnt.push_back(nums[j]); ans.insert(cnt); } return vector<vector<int>>(ans.begin(), ans.end()); } void A(vector<int> &v, int x) { while(x) { v.push_back(x % 2); x /= 2; } } };