[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
        
相关推荐
sword devil9002 分钟前
PYQT实战:智能家居中控
python·智能家居·pyqt
NetX行者3 分钟前
FastMCP:用于构建MCP服务器的开源Python框架
服务器·python·开源
超龄超能程序猿7 分钟前
(3)机器学习小白入门 YOLOv: 解锁图片分类新技能
python·numpy·pandas·scipy
waynaqua34 分钟前
FastAPI开发AI应用一:实现连续多轮对话
python·openai
纨妙38 分钟前
python打卡day59
开发语言·python
waynaqua38 分钟前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
秋难降42 分钟前
Python 知识 “八股”:给有 C 和 Java 基础的你😁😁😁
java·python·c
wuxuanok44 分钟前
Web后端开发-请求响应
java·开发语言·笔记·学习
FF-Studio1 小时前
大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
人工智能·python·深度学习·神经网络·机器学习·语言模型·自然语言处理
Sally璐璐1 小时前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php