Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 72ab477

Browse files
ybian19azl397985856
authored andcommitted
feat: 46.permutations update Python3 implementation (azl397985856#152)
1 parent 119a380 commit 72ab477

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

‎problems/46.permutations.md‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -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
*/
8081
function 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
101104
class 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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /