[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
        
相关推荐
2301_812539675 分钟前
CSS如何引入CSS形状生成器_通过自定义属性实现图形化样式
jvm·数据库·python
吴声子夜歌17 分钟前
Java——接口的细节
java·开发语言·算法
阿拉金alakin19 分钟前
深入理解 Java 锁机制:CAS 原理、synchronized 优化与主流锁策略全总结
java·开发语言
myheartgo-on23 分钟前
Java—方 法
java·开发语言·算法·青少年编程
雨落在了我的手上28 分钟前
如何学习java?
java·开发语言·学习
m0_6091604942 分钟前
Golang怎么实现数据库连接重试_Golang如何在启动时重试连接直到数据库就绪【技巧】
jvm·数据库·python
花米徐1 小时前
技术洞察精选 | 2026年4月28日 — 5月4日
后端·python·flask
神仙别闹1 小时前
基于 C# OpenPGP 的文件管理系统
开发语言·c#
宝贝儿好2 小时前
【LLM】第三章:项目实操案例:智能输入法项目
人工智能·python·深度学习·算法·机器人
m0_624578592 小时前
如何在phpMyAdmin中导入GZIP压缩格式文件_加速传输并突破文件大小限制
jvm·数据库·python