【Leetcode】46. 全排列(Permutations)

No46. 全排列

题目

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例

  • 输入: [1,2,3]
  • 输出:
    [
    [1,2,3],
    [1,3,2],
    [2,1,3],
    [2,3,1],
    [3,1,2],
    [3,2,1]
    ]

解题代码(Python3)

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ori = [x for x in nums]
        res = [[x] for x in nums]
        for i in range(len(nums) - 1):
            res = [x + [y] for x in res for y in ori if y not in x]
        return res

思路:

外层循环次数是数字序列的长度 - 1,建立ori和res两个辅助List进行循环赋值。

复杂度分析:

  • 时间复杂度 O(n^3) 2层的列表推导生成式+1层外循环
  • 空间复杂度 O(n) 3个n长度的List

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Xiao_Spring/article/details/113731372