[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
        
相关推荐
listhi5203 分钟前
基于在线优化的快速模型预测控制(Fast Online MPC)MATLAB实现
开发语言·matlab
gc_229912 分钟前
学习python使用Ultralytics的YOLO26进行姿势估计的基本用法
python·ultralytics·yolo26·姿势估计
CoderCodingNo12 分钟前
【CSP】CSP-J 2025真题 | 多边形 luogu-P14360 (相当于GESP六级水平)
开发语言·c++·算法
2201_7548647814 分钟前
学习日记(2026年3月29日)
人工智能·python·机器学习
一直都在57219 分钟前
AQS详解
java·开发语言
zero159720 分钟前
Python 8天极速入门笔记(大模型工程师专用):第二篇-Python基础入门(变量、数据类型、print输出)
开发语言·笔记·python
koping_wu22 分钟前
【Java并发】CompletableFuture详解:常用API和底层原理
java·开发语言·python
填满你的记忆25 分钟前
《Java 面试常见题型(2026最新版,背完直接能面)》
java·开发语言
:mnong26 分钟前
附图报价系统设计分析2
python·pyqt·openvino
源码之家29 分钟前
计算机毕业设计:基于Python的美食推荐可视化系统 Django框架 可视化 协同过滤推荐算法 推荐系统 食物 食品 大数据 数据分析(建议收藏)✅
python·django·flask·课程设计·推荐算法·美食