题目
在这里插入图片描述

【代码】
在这里插入图片描述

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        n=len(nums)
        ans=[]
        def dfs(first=0):
            if first==n:
                ans.append(nums[:])
            for i in range(first,n):
                nums[first],nums[i]=nums[i],nums[first]
                dfs(first+1)
                nums[i],nums[first]=nums[first],nums[i]
        dfs()
        return ans

【方法2】
在这里插入图片描述

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res=[]
        path=[]
        end=len(nums)
        used=[False]*len(nums)
        depth=0
        def dfs(path,depth):
            if depth==len(nums):
                res.append(path[:])
                return
            for index in range(end):
                if used[index]==True:
                    continue
                used[index]=True
                path.append(nums[index])
                dfs(path,depth+1)
                path.pop()
                used[index]=False
        dfs(path,0)
        return res

版权声明:本文为kz_java原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/kz_java/article/details/127124327