当前位置: 首页 > 后端技术 > Python

力扣-0046.Permutations全排列[Python]

时间:2023-03-26 19:11:22 Python

LeetCode0046.Permutations全排列[Medium][Python][backtracking][DFS]3]输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]问题Leetie给定一个没有重复数字的序列,返回它所有可能的完整排列。示例:输入:[1,2,3]输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]ideasolutiononepermutationsfunctionPython3codefromitertoolsimportpermutationsclass解决方案:defpermute(self,nums:List[int])->List[List[int]]:#solution一:permutationsreturnlist(permutations(nums))方案2递归将已有排列放入path中,当nums为空时表示递归完成,再将path放入res中。Python3代码类解决方案:defpermute(self,nums:List[int])->List[List[int]]:#解决方案二:递归res=[]self.dfs(nums,res,[])returnresdefdfs(self,nums,res,path):如果不是nums:res.append(path)else:foriinrange(len(nums)):self.dfs(nums[:i]+nums[i+1:],res,path+[nums[i]])解3回溯visited数组表示这个位置是否被访问过。Python3代码类解决方案:defpermute(self,nums:List[int])->List[List[int]]:#解决方案三:回溯visited=[0]*len(nums)res=[]defdfs(path):iflen(path)==len(nums):res.append(path)else:foriinrange(len(nums)):ifnotvisited[i]:visited[i]=1dfs(path+[nums[i]])visited[i]=0dfs([])返回res代码地址github链接