[46. Permutations](https://leetcode.com/problems/permutations/)
### 題目描述
Given an array `nums` of distinct integers, return *all the possible permutations.* You can return the answer in **any order**.
### 範例
**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**:
* 1 <= `nums.length` <= 6
* -10 <= `nums[i]` <= 10
* All the integers of `nums` are **unique**.
### 解答
#### Python
內建作弊 by itertools
```python=
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(permutations(nums))
```
```python=
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(arr):
if len(arr) == len(nums):
res.append(arr.copy())
return
for num in nums:
if num not in arr:
arr.append(num)
backtrack(arr)
arr.pop()
backtrack([])
return res
```
> [name=Ron Chen][time=Wed, Aug 2, 2023]
#### C++
``` cpp=
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
backtrack(nums, 0, ans);
return ans;
}
void backtrack(vector<int>& nums, int first, vector<vector<int>>& ans) {
if (first >= nums.size()) {
ans.push_back(nums);
}
for (int i = first; i < nums.size(); i ++) {
swap(nums[first], nums[i]);
backtrack(nums, first + 1, ans);
swap(nums[first], nums[i]);
}
}
};
```
> [name=Jerry Wu][time=2 August, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)