Skip to content

46. Permutations

题目

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

 

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:

Input: nums = [1]
Output: [[1]]

 

Constraints:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.
Related Topics
  • 数组
  • 回溯

  • 👍 3128
  • 👎 0
  • 思路

    • python 中的 shallow copy 数组可使用 list[:] 进行拷贝
    • 回溯的本质是递归加穷举, 用一个等长数组记录是否使用过的位数感觉很巧妙

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def permute(self, nums: List[int]) -> List[List[int]]:
            res = []
    
            def backtrack(path, used):
                if len(path) == len(nums):
                    res.append(path[:])
                    return
    
                for i,  num in enumerate(nums):
                    if not used[i]:
                        used[i] = True
                        path.append(num)
                        backtrack(path, used)
                        path.pop()
                        used[i] = False
    
            backtrack([], [False] * len(nums))
            return res
    
    
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(N * N)
    • 空间复杂度 O(N * N!)