[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
        
相关推荐
小沈同学呀1 分钟前
飞书机器人+Spring AI Function Calling实战-扔掉MCP Client让LLM直接操控工具
java·开发语言·functioncalling·spring ai·飞书机器人
Sam09272 分钟前
【AI 算法精讲 13】朴素贝叶斯:文本分类的基石
人工智能·python·算法·ai
ai生成式引擎优化技术5 分钟前
WSaiOS:面向认知资产与工程化认知流程的智能操作系统架构
python·架构·django·virtualenv·pygame
STLearner7 分钟前
ICML 2026 | 时间序列(Time Series)论文总结【基础模型,生成,分类,异常检测,插补,表示学习和分析等】
论文阅读·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
雨师@7 分钟前
go语言项目--实例化(图书管理)--006
开发语言·后端·golang
Rotion_深9 分钟前
C# 值类型与引用类型 详解
开发语言·jvm·c#
偏爱自由 !13 分钟前
8. 泛型程序设计
java·开发语言·windows
冰暮流星14 分钟前
python之flask框架讲解-准备
开发语言·python·flask
ch.ju15 分钟前
Java Programming Chapter 4——Class loading
java·开发语言
Huangjin007_19 分钟前
【C++11篇(二)】右值引用、移动语义保姆级讲解!
开发语言·c++