Given a sequence without repeated numbers, return all possible permutations.
Example: Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1 ,2],
[3,2,1]
]Source: LeetCode
Link: https://leetcode-cn.com/problems/permutations
Method 1: This method mainly uses the backtracking method,
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
track=[]
res=[]
def arrange(nums,track):
if len(track)==len(nums):
# 由于list是可变对象,因此,这里要用[:]取到具体的值,再append进res中。
res.append(track[:])
return
for i in nums:
if i in track:
# 如果nums数值已在搜寻表中,继续下一轮
continue
# 添加路径
track.append(i)
arrange(nums,track)
# 对路径进行回溯,将原添加进的值移除
track.pop()
arrange(nums,track)
return res
Method 2:
It mainly uses the recursive iterative process to perform different splicing of the elements on the list to traverse various possible values.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def cur(nums, temp):
if not nums:
# 将中间结果加入结果集
res.append(temp)
return
for i in range(len(nums)):
# 利用递归的迭代进行结果遍历
cur(nums[:i] + nums[i+1:], temp + [nums[i]])
cur(nums, [])
return res
This is the least amount of code I have seen to solve the whole arrangement.
ps: when you have time to make up