[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
        
相关推荐
星河耀银海3 分钟前
C++开发入门——环境搭建与第一个程序
开发语言·c++·策略模式
还不秃顶的计科生7 分钟前
defaultdict讲解
开发语言·javascript·ecmascript
花归去12 分钟前
echarts 柱状图包含右侧进度
开发语言·前端·javascript
wjs202413 分钟前
Java 数组
开发语言
码农水水14 分钟前
大疆Java面试被问:TCC事务的悬挂、空回滚问题解决方案
java·开发语言·人工智能·面试·职场和发展·单元测试·php
Hooray1116 分钟前
前后端分离_案例学习_Python+Flask+VUE3
后端·python·学习·flask
qq_25183645719 分钟前
基于java Web 个人网站系统设计与实现
java·开发语言·数据库
小二·25 分钟前
Python 学习教程(第2篇):用 Flask 开发你的第一个 Web 应用
python·学习·flask
Eternity∞31 分钟前
基于Linux系统vim编译器情况下的C语言学习
linux·c语言·开发语言·学习·vim
周末吃鱼31 分钟前
Lambda作用域
java·开发语言