@@ -40,10 +40,11 @@ Output:
4040- 回溯法
4141- backtrack 解题公式
4242
43-
4443## 代码
4544
46- * 语言支持: Javascript,Python3
45+ * 语言支持: Javascript, Python
46+
47+ Javascript Code:
4748
4849``` js
4950/*
@@ -60,10 +61,10 @@ Output:
6061 * Testcase Example: '[1,2,3]'
6162 *
6263 * Given a collection of distinct integers, return all possible permutations.
63- *
64+ *
6465 * Example:
65- *
66- *
66+ *
67+ *
6768 * Input: [1,2,3]
6869 * Output:
6970 * [
@@ -74,8 +75,8 @@ Output:
7475 * [3,1,2],
7576 * [3,2,1]
7677 * ]
77- *
78- *
78+ *
79+ *
7980 */
8081function backtrack (list , tempList , nums ) {
8182 if (tempList .length === nums .length ) return list .push ([... tempList]);
@@ -96,13 +97,16 @@ var permute = function(nums) {
9697 return list
9798};
9899```
99- Python3 Code:
100+
101+ Python Code:
102+
100103``` Python
101104class Solution :
102105 def permute (self , nums : List[int ]) -> List[List[int ]]:
103106 """ itertools库内置了这个函数"""
107+ import itertools
104108 return itertools.permutations(nums)
105-
109+
106110 def permute2 (self , nums : List[int ]) -> List[List[int ]]:
107111 """ 自己写回溯法"""
108112 res = []
@@ -119,6 +123,21 @@ class Solution:
119123 _backtrace(left_nums, p_list)
120124 _backtrace(nums, [])
121125 return res
126+
127+ def permute3 (self , nums : List[int ]) -> List[List[int ]]:
128+ """ 回溯的另一种写法"""
129+ res = []
130+ length = len (nums)
131+ def _backtrack (start = 0 ):
132+ if start == length:
133+ # nums[:] 返回 nums 的一个副本,指向新的引用,这样后续的操作不会影响已经已知解
134+ res.append(nums[:])
135+ for i in range (start, length):
136+ nums[start], nums[i] = nums[i], nums[start]
137+ _backtrack(start+ 1 )
138+ nums[start], nums[i] = nums[i], nums[start]
139+ _backtrack()
140+ return res
122141```
123142
124143## 相关题目
@@ -132,4 +151,3 @@ class Solution:
132151- [ 90.subsets-ii] ( ./90.subsets-ii.md )
133152- [ 113.path-sum-ii] ( ./113.path-sum-ii.md )
134153- [ 131.palindrome-partitioning] ( ./131.palindrome-partitioning.md )
135-
0 commit comments