LeetCode 78. Subsets
LeetCode 78. https://leetcode.com/problems/subsets/
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> out; subsetsDFS(nums, 0, res, out); return res; } void subsetsDFS (vector<int>& nums, int pos, vector<vector<int>>& res, vector<int>& out) { res.push_back(out); for (int i = pos; i < nums.size(); i++) { out.push_back(nums[i]); subsetsDFS(nums, i + 1, res, out); out.pop_back(); } } };
|
LeetCode 90.
LeetCode 90. https://leetcode.com/problems/subsets-ii/
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: vector<vector<int>> subsetsWithDup(vector<int> &nums) { if (nums.empty()) return {}; vector<vector<int>> res(1); sort(nums.begin(), nums.end()); int size = 1, last = nums[0]; for (int i = 0; i < nums.size(); ++i) { if (last != nums[i]) { last = nums[i]; size = res.size(); } int newSize = res.size(); for (int j = newSize - size; j < newSize; ++j) { res.push_back(res[j]); res.back().push_back(nums[i]); } } return res; } };
|