notes/OJ notes/pages/Leetcode Permutations.md

114 lines
1.9 KiB
Markdown
Raw Normal View History

2022-07-20 14:25:33 +08:00
# Leetcode Permutations
#### 2022-07-20 14:16
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
> #algorithm #backtrack
>
2022-07-20 14:25:33 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
> #coding_problem #difficulty-medium
>
2022-07-20 14:25:33 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode
>
2022-07-20 14:25:33 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-20 14:25:33 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-20 14:25:33 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-20 14:25:33 +08:00
- [Link to problem](https://leetcode.com/problems/permutations/)
2022-09-03 15:41:36 +08:00
---
2022-07-20 14:25:33 +08:00
### Problem
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
#### Examples
**Example 1:**
```
**Input:** nums = [1,2,3]
**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
```
**Example 2:**
```
**Input:** nums = [0,1]
**Output:** [[0,1],[1,0]]
```
**Example 3:**
```
**Input:** nums = [1]
**Output:** [[1]]
```
#### Constraints
**Constraints:**
2022-09-03 15:41:36 +08:00
- `1 <= nums.length <= 6`
- `-10 <= nums[i] <= 10`
- All the integers of `nums` are **unique**.
2022-07-20 14:25:33 +08:00
### Thoughts
> [!summary]
> This is a #backtrack problem
Backtrack problem, see alse [[Leetcode Combinations]]
### Solution
```cpp
class Solution {
void backtrack(vector<vector<int>> &ans, vector<int> &combs, bool unused[],
vector<int> &nums, int n, int k) {
// if the end is hit, append it to ans.
if (k == 0) {
ans.push_back(combs);
} else {
// iterate over the unused vector
for (int i = 0; i < n; i++) {
if (!unused[i]) {
continue;
}
unused[i] = false;
combs.push_back(nums[i]);
backtrack(ans, combs, unused, nums, n, k - 1);
combs.pop_back();
unused[i] = true;
}
}
}
public:
vector<vector<int>> permute(vector<int> &nums) {
// This can be modified from combinations
vector<vector<int>> ans = {};
vector<int> combs = {};
int size = nums.size();
bool unused[size];
for (int i = 0; i < size; i++) {
unused[i] = true;
}
backtrack(ans, combs, unused, nums, size, size);
return ans;
}
};
2022-09-03 15:41:36 +08:00
```