Given a collection of distinct integers, 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]
]
一个深度优先遍历的应用。
深度优先遍历过程中的两个参数:nums记录剩余的数字,path记录已经按顺序选过的数字。
dfs过程中path+[nums[i]]不能用append的方式,会报错'NoneType' object has no attribute 'append'。
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
final=[]
def dfs(nums, path):
if len(nums)==0:
final.append(path)
for i in range(len(nums)):
dfs(nums[:i]+nums[i+1:], path+[nums[i]])
dfs(nums,[])
return final

本文介绍了一种使用深度优先遍历算法求解给定整数集合的所有可能排列的方法。通过递归调用,从给定的整数集合中逐个选择元素,形成所有可能的排列组合。
430





