diff --git a/OJ notes/pages/Leetcode Subsets.md b/OJ notes/pages/Leetcode Subsets.md new file mode 100644 index 0000000..4ff8c1e --- /dev/null +++ b/OJ notes/pages/Leetcode Subsets.md @@ -0,0 +1,103 @@ +# Leetcode Subsets + +#### 2022-07-22 16:16 + +> ##### Algorithms: +> #algorithm #backtrack +> ##### Data structures: +> #DS #vector +> ##### Difficulty: +> #coding_problem #difficulty-medium +> ##### Additional tags: +> #leetcode +> ##### Revisions: +> N/A + +##### Related topics: +```expander +tag:#backtrack +``` + + + +##### Links: +- [Link to problem](https://leetcode.com/problems/subsets/) +___ +### Problem + +Given an integer array `nums` of **unique** elements, return _all possible subsets (the power set)_. + +The solution set **must not** contain duplicate subsets. Return the solution in **any order**. + +#### Examples + +**Example 1:** + +``` +**Input:** nums = [1,2,3] +**Output:** [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] +``` + +**Example 2:** + +``` +**Input:** nums = [0] +**Output:** [[],[0]] +``` + +#### Constraints + +- `1 <= nums.length <= 10` +- `-10 <= nums[i] <= 10` +- All the numbers of `nums` are **unique**. + +### Thoughts + +> [!summary] +> This is a super simple #backtrack problem. + +It asked for combinations, so this is a backtrack problem. + +go from index 0 to last one, in each iteration, you have two choices: +- Add this number +- Don't add this number +And we try different combinations at the same level, aka. backtracking. + +#### Pseudo code: + +- When loc == size, append combination to answer +- Else, start trying different solutions: + - Append this element to combs and backtrack + - pop this from combs and backtrack + +### Solution + +```cpp +class Solution { + vector> ans; + vector combs; + void backtrack(vector &nums, int nextLoc) { + // We don't require min amount of location + + if (nextLoc == nums.size()) { + ans.push_back(combs); + } else { + combs.push_back(nums[nextLoc]); + backtrack(nums, nextLoc + 1); + + combs.pop_back(); + backtrack(nums, nextLoc + 1); + } + } + +public: + vector> subsets(vector &nums) { + // Backtracking for accumulating combinations. + ans = {}; + combs = {}; + backtrack(nums, 0); + + return ans; + } +}; +``` \ No newline at end of file