[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
        
相关推荐
金銀銅鐵7 分钟前
[Java] 用GUI展示class文件顶层的 access_flags
后端·python·ai编程
kimnoic28 分钟前
Python操作xlwings的实例详解
开发语言·python
2601_9578838432 分钟前
2026年10月 外星人笔记本维修须知
python·电脑
泡茶喝茶写代码40 分钟前
A股量化数据工程:从 REST 接口到策略信号(第 17 篇):创新高与新低扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
栗子~~1 小时前
java - logstash-logback-encoder 集成 demo
java·开发语言·logback
VIP_CQCRE1 小时前
用 Ace Data Cloud 接入 OpenAI 兼容语音转文字:一份能直接运行的 API 指南
python·openai·api·语音识别·acedatacloud
ESDWAN1 小时前
跨境网络频繁掉线怎么排查?从企业内网到 SD-WAN 链路的故障诊断
开发语言·网络·php
程序员zgh2 小时前
C++ erase() 函数用法
c语言·开发语言·c++·学习
lee_tianbai2 小时前
Java SSM 电影票预定系统|完整前后端项目,开箱即用(源码分享)
java·开发语言·数据库
砚底藏山河2 小时前
python量化入门:多周期数据对齐统一时间轴
java·数据库·python·金融·maven