1
1
## 题目地址
2
+
2
3
https://leetcode.com/problems/permutations/description/
3
4
4
5
## 题目描述
6
+
5
7
```
6
8
Given a collection of distinct integers, return all possible permutations.
7
9
@@ -20,13 +22,17 @@ Output:
20
22
21
23
```
22
24
25
+ ## 前置知识
26
+
27
+ - 回溯法
28
+
23
29
## 思路
24
30
25
31
这道题目是求集合,并不是` 求极值 ` ,因此动态规划不是特别切合,因此我们需要考虑别的方法。
26
32
27
33
这种题目其实有一个通用的解法,就是回溯法。
28
34
网上也有大神给出了这种回溯法解题的
29
- [ 通用写法] ( https://leetcode.com/problems/combination-sum/discuss/16502/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning) ) ,这里的所有的解法使用通用方法解答。
35
+ [ 通用写法] ( < https://leetcode.com/problems/combination-sum/discuss/16502/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning) > ) ,这里的所有的解法使用通用方法解答。
30
36
除了这道题目还有很多其他题目可以用这种通用解法,具体的题目见后方相关题目部分。
31
37
32
38
我们先来看下通用解法的解题思路,我画了一张图:
@@ -42,7 +48,7 @@ Output:
42
48
43
49
## 代码
44
50
45
- * 语言支持: Javascript, Python3
51
+ - 语言支持: Javascript, Python3
46
52
47
53
Javascript Code:
48
54
@@ -79,31 +85,33 @@ Javascript Code:
79
85
*
80
86
*/
81
87
function backtrack (list , tempList , nums ) {
82
- if (tempList .length === nums .length ) return list .push ([... tempList]);
83
- for (let i = 0 ; i < nums .length ; i++ ) {
84
- if (tempList .includes (nums[i])) continue ;
85
- tempList .push (nums[i]);
86
- backtrack (list, tempList, nums);
87
- tempList .pop ();
88
- }
88
+ if (tempList .length === nums .length ) return list .push ([... tempList]);
89
+ for (let i = 0 ; i < nums .length ; i++ ) {
90
+ if (tempList .includes (nums[i])) continue ;
91
+ tempList .push (nums[i]);
92
+ backtrack (list, tempList, nums);
93
+ tempList .pop ();
94
+ }
89
95
}
90
96
/**
91
97
* @param {number[]} nums
92
98
* @return {number[][]}
93
99
*/
94
- var permute = function (nums ) {
95
- const list = [];
96
- backtrack (list, [], nums)
97
- return list
100
+ var permute = function (nums ) {
101
+ const list = [];
102
+ backtrack (list, [], nums);
103
+ return list;
98
104
};
99
105
```
106
+
100
107
Python3 Code:
108
+
101
109
``` Python
102
110
class Solution :
103
111
def permute (self , nums : List[int ]) -> List[List[int ]]:
104
112
""" itertools库内置了这个函数"""
105
113
return itertools.permutations(nums)
106
-
114
+
107
115
def permute2 (self , nums : List[int ]) -> List[List[int ]]:
108
116
""" 自己写回溯法"""
109
117
res = []
0 commit comments