[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
        
相关推荐
张晓~183399481211 分钟前
碰一碰发视频 系统源码 /PHP 语言开发方案
开发语言·线性代数·矩阵·aigc·php·音视频·文心一言
代码不停3 分钟前
Java前缀和算法题目练习
java·开发语言·算法
豆沙沙包?3 分钟前
2025年--Lc200- 414. 第三大的数(大根堆)--Java版
java·开发语言
一念&9 分钟前
每日一个C语言知识:C 指针
c语言·开发语言
涤生z11 分钟前
list.
开发语言·数据结构·c++·学习·算法·list
xxxxxxllllllshi14 分钟前
Java中Elasticsearch完全指南:从零基础到实战应用
java·开发语言·elasticsearch·面试·职场和发展·jenkins
wu_jing_sheng028 分钟前
Python中使用HTTP 206状态码实现大文件下载的完整指南
开发语言·前端·python
程序员大雄学编程37 分钟前
「用Python来学微积分」2. 函数图像的变换
python·数学·微积分
励志不掉头发的内向程序员1 小时前
【Linux系列】掌控 Linux 的脉搏:深入理解进程控制
linux·运维·服务器·开发语言·学习
梵得儿SHI1 小时前
Java 反射机制深度解析:从对象创建到私有成员操作
java·开发语言·class对象·java反射机制·操作类成员·三大典型·反射的核心api