【回溯-中等】46. 全排列

【题目】
【回溯-中等】46. 全排列_第1张图片

【代码】
【回溯-中等】46. 全排列_第2张图片

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】
【回溯-中等】46. 全排列_第3张图片

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

你可能感兴趣的:(刷题,leetcode,深度优先,算法)