Skip to content

Commit

Permalink
feat: 46.permutations update Python3 implementation (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
ybian19 authored and azl397985856 committed Aug 28, 2019
1 parent cdbbc23 commit 146c858
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions problems/46.permutations.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ Output:
- 回溯法
- backtrack 解题公式


## 代码

* 语言支持: Javascript,Python3
* 语言支持: Javascript, Python

Javascript Code:

```js
/*
Expand All @@ -60,10 +61,10 @@ Output:
* Testcase Example: '[1,2,3]'
*
* Given a collection of distinct integers, return all possible permutations.
*
*
* Example:
*
*
*
*
* Input: [1,2,3]
* Output:
* [
Expand All @@ -74,8 +75,8 @@ Output:
* ⁠ [3,1,2],
* ⁠ [3,2,1]
* ]
*
*
*
*
*/
function backtrack(list, tempList, nums) {
if (tempList.length === nums.length) return list.push([...tempList]);
Expand All @@ -96,13 +97,16 @@ var permute = function(nums) {
return list
};
```
Python3 Code:

Python Code:

```Python
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
"""itertools库内置了这个函数"""
import itertools
return itertools.permutations(nums)

def permute2(self, nums: List[int]) -> List[List[int]]:
"""自己写回溯法"""
res = []
Expand All @@ -119,6 +123,21 @@ class Solution:
_backtrace(left_nums, p_list)
_backtrace(nums, [])
return res

def permute3(self, nums: List[int]) -> List[List[int]]:
"""回溯的另一种写法"""
res = []
length = len(nums)
def _backtrack(start=0):
if start == length:
# nums[:] 返回 nums 的一个副本,指向新的引用,这样后续的操作不会影响已经已知解
res.append(nums[:])
for i in range(start, length):
nums[start], nums[i] = nums[i], nums[start]
_backtrack(start+1)
nums[start], nums[i] = nums[i], nums[start]
_backtrack()
return res
```

## 相关题目
Expand All @@ -132,4 +151,3 @@ class Solution:
- [90.subsets-ii](./90.subsets-ii.md)
- [113.path-sum-ii](./113.path-sum-ii.md)
- [131.palindrome-partitioning](./131.palindrome-partitioning.md)

0 comments on commit 146c858

Please sign in to comment.