[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
        
相关推荐
兮动人2 小时前
C语言之指针入门
c语言·开发语言·c语言之指针入门
ada7_2 小时前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
我送炭你添花3 小时前
Pelco KBD300A 模拟器:06+5.串口实现的逻辑优化、配置管理与协议完善(二次迭代)
python·运维开发
databook3 小时前
前注意加工:让你的图表抓住读者的眼球
python·数据分析·数据可视化
知行学思3 小时前
Python配置管理完全指南:从dotenv到pydantic_settings
数据库·python·fastapi·环境变量·配置管理·pydantic·dotenv
nbsaas-boot3 小时前
Go 项目中如何正确升级第三方依赖(Go Modules 实战指南)
开发语言·后端·golang
wadesir4 小时前
C++基本数据类型详解(零基础掌握C++核心数据类型)
java·开发语言·c++
skywalk81634 小时前
wow文件处理trinitycore的文件处理
开发语言·游戏
一路往蓝-Anbo5 小时前
STM32单线串口通讯实战(五):RTOS架构 —— 线程安全与零拷贝设计
c语言·开发语言·stm32·单片机·嵌入式硬件·观察者模式·链表
leiming65 小时前
c++ map容器
开发语言·c++·算法