[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
        
相关推荐
ExiFengs11 小时前
Java使用策略模式实现多实体通用操作的优雅设计
java·开发语言·设计模式·策略模式
茶本无香11 小时前
设计模式之三—工厂模式:灵活对象创建的艺术
java·开发语言·设计模式·工厂模式
超级无敌大学霸11 小时前
c语言整型提升
c语言·开发语言
困惑阿三11 小时前
利用 Flexbox 实现无需媒体查询(Media Queries)的自动响应式网格。
开发语言·前端·javascript
曲幽11 小时前
FastAPI数据库实战:从SQLAlchemy原理到高效连接管理,告别性能瓶颈
python·sqlite·flask·fastapi·web·sqlalchemy·db
m0_7482500311 小时前
C++ 预处理器
开发语言·c++
dagouaofei11 小时前
2026 年工作计划 PPT 制作,AI 自动生成是否真的省时
python·powerpoint
袁袁袁袁满12 小时前
Python使用uuid生成唯一密钥uid详细教程
开发语言·python·uuid·唯一密钥uid
Logan Lie12 小时前
Go 反射(Reflection)详解:从入门到实践
开发语言·后端·golang
爱装代码的小瓶子12 小时前
【c++进阶】c++11下类的新变化以及Lambda函数和封装器
java·开发语言·c++