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

leetcode46.全编排

时间:2023-03-26 19:29:34 Python

https://leetcode-cn.com/probl...简单的深度优先遍历。我试过list的append和pop,直接用下标修改list的值。似乎对结果影响不大。类解决方案:defpermute(self,nums:List[int])->List[List[int]]:ans=[]n=len(nums)f=[False]*nl=[]defdfs(i):ifi==n:ans.append(l[::])returnforjinrange(n):ifnotf[j]:l.append(nums[j])f[j]=Truedfs(i+1)f[j]=Falsel.pop()dfs(0)returnans执行时间:40ms,击败所有Python3提交的88.14%用户内存消耗:13.1MB,击败所有Python3提交59.71%的用户类别解决方案:defpermute(self,nums:List[int])->List[List[int]]:ans=[]n=len(nums)f=[False]*nl=[0]*ndefdfs(i):如果i==n:ans.append(l[::])returnforjinrange(n):如果不是f[j]:l[i]=nums[j]f[j]=Truedfs(i+1)f[j]=Falsedfs(0)returnans执行时间:40毫秒,击败所有Python3提交的88.14%用户内存消耗:13.1MB,击败所有Python3提交的59.50%欢迎来到我的博客:https://codeplot.top/我的博客分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/