Skip to content

Commit eb6c9e1

Browse files
committed
chore: add daily leetcode post 46.全排列
1 parent 2413f81 commit eb6c9e1

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
title: 46.permutations
3+
date: 24/3/2025
4+
tags:
5+
- Python
6+
- '9021'
7+
- tree
8+
abbrlink: d567a4cd
9+
---
10+
11+
# Description:
12+
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
13+
14+
Example 1:
15+
16+
Input: nums = [1,2,3]
17+
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
18+
Example 2:
19+
20+
Input: nums = [0,1]
21+
Output: [[0,1],[1,0]]
22+
Example 3:
23+
24+
Input: nums = [1]
25+
Output: [[1]]
26+
27+
28+
# Thinking:
29+
This question is more like a tree problem.
30+
like the tree below:
31+
```shell
32+
dfs(0): nums = [1,2,3]
33+
|
34+
|-- i=0: swap(0,0) -> [1,2,3]
35+
| |
36+
| |-- dfs(1)
37+
| |-- i=1: swap(1,1) -> [1,2,3]
38+
| | |-- dfs(2): append [1,2,3]
39+
| |-- i=2: swap(1,2) -> [1,3,2]
40+
| |-- dfs(2): append [1,3,2]
41+
|
42+
|-- i=1: swap(0,1) -> [2,1,3]
43+
| |
44+
| |-- dfs(1)
45+
| |-- i=1: swap(1,1) -> [2,1,3]
46+
| | |-- dfs(2): append [2,1,3]
47+
| |-- i=2: swap(1,2) -> [2,3,1]
48+
| |-- dfs(2): append [2,3,1]
49+
|
50+
|-- i=2: swap(0,2) -> [3,2,1]
51+
|
52+
|-- dfs(1)
53+
|-- i=1: swap(1,1) -> [3,2,1]
54+
| |-- dfs(2): append [3,2,1]
55+
|-- i=2: swap(1,2) -> [3,1,2]
56+
|-- dfs(2): append [3,1,2]
57+
58+
```
59+
We swap the current position index with each possible candidate `i` from `index` to the end. They can be seen as left and right pointers: `index` determines which position we're filling, and `i` tries different numbers to place there.
60+
61+
Before the recursive call, we swap `nums[i]` and `nums[index]` to try placing a new number at position index. If we reach the last position (`index == len(nums) - 1`), we add the current permutation to the answer list.
62+
After recursion, we swap back to restore the original state (backtracking).
63+
64+
# Code:
65+
```python
66+
class Solution:
67+
def permute(self, nums: List[int]) -> List[List[int]]:
68+
# index
69+
def dfs(index):
70+
# Reach the last element
71+
if index == len(nums) - 1:
72+
res.append(list(nums))
73+
return
74+
for i in range(index, len(nums)):
75+
nums[i], nums[index] = nums[index], nums[i]
76+
dfs(index + 1)
77+
nums[i], nums[index] = nums[index], nums[i]
78+
79+
res = []
80+
dfs(0)
81+
return res
82+
```

0 commit comments

Comments
 (0)