LeetCode 刷题记录: 46. Permutations [Python]

原题

https://leetcode.com/problems/permutations/

Given a collection of distinct integers, return all possible permutations.

思路

Backtrack。当temp长度等于所有数字时,添加进结果。否则遍历数字,每个数字添加进temp中,进行下一次迭代。当temp中存在相同数字时跳过。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if not nums: return [[]]
result=[]
self.backtrack(nums,[],result)
return result
def backtrack(self, nums, temp,result):
if len(temp)==len(nums): result.append(temp[:])
else:
for num in nums:
if num in temp: continue
temp.append(num)
self.backtrack(nums,temp,result)
temp.pop()

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×