[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
        
相关推荐
菜鸟~noob2337 小时前
【太空电子战】午夜锤行动中的电磁静默区:可逆干扰的实战验证【含matlab代码】
linux·开发语言·matlab·电子战
databook7 小时前
时间序列分解:从噪声中提取有效信号
python·数据挖掘·数据分析
坤坤子吖7 小时前
Python基础语法学习:条件、循环与程序控制
开发语言·笔记·python·学习
吠品7 小时前
volatile到底在拦什么:SysTick->VAL读的哪格
java·服务器·开发语言
伞伞悦读7 小时前
【第53期】有序插入把二叉搜索树变成链:别只看“树”的名字
python
郝学胜_神的一滴8 小时前
AI 编程智能体 04:一文看懂智能体的核心能力与概念辨析
人工智能·python
一缕82年的清风8 小时前
实战指南:如何把现有 REST API 工业级封装为 MCP(Model Context Protocol)服务
python·mcp
狼与自由8 小时前
python打包
开发语言·python
进击的雷神8 小时前
OpenClaw 太重、启动太慢?我试了试这个 Rust 重写的轻量版 AI 助手网关
开发语言·人工智能·rust·zeroclaw
辛苦才能8 小时前
C++ 红黑树(上):五条规则背后的近似平衡与插入的三类情况
开发语言·c++