[NeetCode 150] Permutations

Permutations

Given an array nums of unique integers, return all the possible permutations. You may 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 = [7]

Output: [[7]]

Constraints:

复制代码
1 <= nums.length <= 6
-10 <= nums[i] <= 10

Solutions

To elegantly solve this problem, we can look through the process of permutation:

  1. Pick a number from list and put as the first one.
  2. Pick the next number from the rest numbers in list.
  3. Repeat step 2 until all numbers are placed.
  4. Repeat step 1-3 to go through all possible permutations.

In practice, this process can be implemented via DFS. At each step of DFS, we pick up a number from rests and put it to the place corresponding to current DFS step (using swap). The recursion ends when the depth of DFS reach the length of array.

Code

py 复制代码
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ans = []
        def pick_place(le, ri):
            if le==ri:
                ans.append(nums[:])
                return
            for i in range(le, ri):
                nums[le], nums[i] = nums[i], nums[le]
                pick_place(le+1, ri)
                nums[le], nums[i] = nums[i], nums[le]
        
        pick_place(0, len(nums))
        return ans
        
相关推荐
山土成旧客几秒前
【Python学习打卡-Day30】模块化编程:从“单兵作战”到“军团指挥”
开发语言·python·学习
世转神风-2 分钟前
qt-union-联合体基础讲解
开发语言·qt
moxiaoran57532 分钟前
Go语言的数据类型转换
开发语言·后端·golang
秋邱4 分钟前
Java包装类:基本类型与包装类转换、自动装箱与拆箱原理
java·开发语言·python
海上彼尚4 分钟前
Go之路 - 8.go的接口
开发语言·golang·xcode
乐茵lin5 分钟前
golang context底层设计探究
开发语言·后端·golang·大学生·设计·context·底层源码
lkbhua莱克瓦246 分钟前
基础-约束
android·开发语言·数据库·笔记·sql·mysql·约束
拉拉拉拉拉拉拉马8 分钟前
感知机(Perceptron)算法详解
人工智能·python·深度学习·算法·机器学习
万邦科技Lafite9 分钟前
淘宝开放API获取订单信息教程(2025年最新版)
java·开发语言·数据库·人工智能·python·开放api·电商开放平台
CoderCodingNo10 分钟前
【GESP】C++五级真题(前缀和思想考点) luogu-P10719 [GESP202406 五级] 黑白格
开发语言·c++·算法