46. 全排列(中等)(LCR 083)

https://leetcode.cn/problems/permutations/

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        # 难度:☆☆☆
        # 标签:回溯
        # 排列:元素无重不可复选
        # from copy import deepcopy
        # path, result, n = [], [], len(nums)  # 子集组合排列回溯三剑客
        # used = [0] * n  # 排列专属

        # def backtrack(start):
        #     if len(path) == n:  # 到达叶子节点,收割结果
        #         result.append(deepcopy(path))  # result.append(path[:])
        #         return
        #     # for循环横向遍历
        #     for i in range(n):  # 排列的range里只有n,子集和组合是(start, n)
        #         if used[i] == 1:
        #             continue       
        #         # 做选择
        #         used[i] = 1
        #         path.append(nums[i])
        #         # 递归,纵向遍历,进入下一层回溯
        #         # 每层遍历都是从start开始
        #         backtrack(i)
        #         # backtrack(start)
        #         # 取消选择
        #         used[i] = 0
        #         path.pop()
        # backtrack(0)
        # return result

        # 不使用used
        from copy import deepcopy
        path, result, n = [], [], len(nums)
        def backtrack(start):
            if len(path) == n:
                result.append(path[:])
                return
            for i in range(n):
                if nums[i] in path:
                    continue
                path.append(nums[i])
                backtrack(nums[i])
                path.pop()
        backtrack(0)
        return result

你可能感兴趣的:(回溯与子集组合排列切割,python,数据结构,算法,leetcode)