[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
        
相关推荐
Davina_yu几秒前
Windows 下升级 R 语言至最新版
开发语言·windows·r语言
阿珊和她的猫3 分钟前
IIFE:JavaScript 中的立即调用函数表达式
开发语言·javascript·状态模式
vibag17 分钟前
构建智能体与工具调用
python·语言模型·大模型·langgraph
listhi52018 分钟前
卷积码编码和维特比译码的MATLAB仿真程序
开发语言·matlab
小途软件21 分钟前
高校宿舍访客预约管理平台开发
java·人工智能·pytorch·python·深度学习·语言模型
yuan1999725 分钟前
基于主成分分析(PCA)的故障诊断MATLAB仿真
开发语言·matlab
J_liaty26 分钟前
Java版本演进:从JDK 8到JDK 21的特性革命与对比分析
java·开发语言·jdk
-dcr30 分钟前
49.python自动化
运维·python·自动化
code bean38 分钟前
Flask图片服务在不同网络接口下的路径解析问题及解决方案
后端·python·flask
翔云 OCR API1 小时前
发票查验接口详细接收参数说明-C#语言集成完整示例-API高效财税管理方案
开发语言·c#