notes/OJ notes/pages/Leetcode Subsets.md

112 lines
2 KiB
Markdown
Raw Normal View History

2022-07-22 16:24:29 +08:00
# Leetcode Subsets
#### 2022-07-22 16:16
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
> #algorithm #backtrack
>
2022-07-22 16:24:29 +08:00
> ##### Data structures:
2022-09-03 15:41:36 +08:00
>
> #DS #vector
>
2022-07-22 16:24:29 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-09-06 20:22:48 +08:00
> #coding_problem #difficulty_medium
2022-09-03 15:41:36 +08:00
>
2022-07-22 16:24:29 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode
>
2022-07-22 16:24:29 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-22 16:24:29 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-22 16:24:29 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-22 16:24:29 +08:00
- [Link to problem](https://leetcode.com/problems/subsets/)
2022-09-03 15:41:36 +08:00
---
2022-07-22 16:24:29 +08:00
### 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
2022-09-03 15:41:36 +08:00
- `1 <= nums.length <= 10`
- `-10 <= nums[i] <= 10`
- All the numbers of `nums` are **unique**.
2022-07-22 16:24:29 +08:00
### 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:
2022-09-03 15:41:36 +08:00
2022-07-22 16:24:29 +08:00
- Add this number
- Don't add this number
2022-09-03 15:41:36 +08:00
And we try different combinations at the same level, aka. backtracking.
2022-07-22 16:24:29 +08:00
#### Pseudo code:
- When loc == size, append combination to answer
- Else, start trying different solutions:
2022-09-03 15:41:36 +08:00
- Append this element to combs and backtrack
- pop this from combs and backtrack
2022-07-22 16:24:29 +08:00
### Solution
```cpp
class Solution {
vector<vector<int>> ans;
vector<int> combs;
void backtrack(vector<int> &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<vector<int>> subsets(vector<int> &nums) {
// Backtracking for accumulating combinations.
ans = {};
combs = {};
backtrack(nums, 0);
return ans;
}
};
2022-09-03 15:41:36 +08:00
```