Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
这类有重复值的情况怎么处理
SubSets的算法
1 class Solution { 2 public: 3 std::vector<std::vector<int> > subsets(std::vector<int> &nums) { 4 std::sort(nums.begin(), nums.end()); 5 std::vector<std::vector<int> > res; 6 std::vector<int> vec; 7 subsets(res, nums, vec, 0); 8 return res; 9 } 10 private: 11 void subsets(std::vector<std::vector<int> > &res, std::vector<int> &nums, std::vector<int> &vec, int begin) { 12 res.push_back(vec); 13 for (int i = begin; i != nums.size(); ++i) { 14 vec.push_back(nums[i]); 15 subsets(res, nums, vec, i + 1); 16 vec.pop_back(); 17 } 18 } 19 };
subsets([1,2,3,4]) = [] // push(1) [1, subsets([2,3,4])] // if push N times in subsets([2,3,4]), the pop times is also N, so vec is also [1] after backtrack. // pop(), push(2) [2, subsets([3,4])] // pop(), push(3) [3, subsets([4])] // pop(), push(4) [4, subsets([])] // pop()
Subsets II的解法
1 class Solution { 2 public: 3 std::vector<std::vector<int> > subsetsWithDup(std::vector<int> &nums) { 4 std::sort(nums.begin(), nums.end()); 5 std::vector<std::vector<int> > res; 6 std::vector<int> vec; 7 subsetsWithDup(res, nums, vec, 0); 8 return res; 9 } 10 private: 11 void subsetsWithDup(std::vector<std::vector<int> > &res, std::vector<int> &nums, std::vector<int> &vec, int begin) { 12 res.push_back(vec); 13 for (int i = begin; i != nums.size(); ++i) 14 if (i == begin || nums[i] != nums[i - 1]) { 15 vec.push_back(nums[i]); 16 subsetsWithDup(res, nums, vec, i + 1); 17 vec.pop_back(); 18 } 19 } 20 };