本文共 619 字,大约阅读时间需要 2 分钟。
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
转载地址:http://kcrbb.baihongyu.com/