[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
        
相关推荐
Larry_Yanan33 分钟前
Qt多进程(六)共享内存和信号量
开发语言·qt
BD_Marathon33 分钟前
bean基础配置
java·开发语言
东方忘忧36 分钟前
Qt使用QDesktopServices::openUrl打开系统默认应用(如浏览器,文件,文件夹和邮件)
开发语言·qt
计算机内卷的N天37 分钟前
qt的模态和非模态状态
开发语言·qt
半桶水专家8 小时前
go语言中的结构体嵌入详解
开发语言·后端·golang
在屏幕前出油9 小时前
二、Python面向对象编程基础——理解self
开发语言·python
阿方索9 小时前
python文件与数据格式化
开发语言·python
weixin_4407305010 小时前
java结构语句学习
java·开发语言·学习
JIngJaneIL11 小时前
基于java+ vue医院管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
量子联盟11 小时前
功能完整的PHP站点导航管理系统php程序;开源免费下载
开发语言·php