[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
        
相关推荐
生信大表哥1 小时前
单细胞测序分析(五)降维聚类&数据整合
linux·python·聚类·数信院生信服务器
故事不长丨1 小时前
C#定时器与延时操作的使用
开发语言·c#·.net·线程·定时器·winform
hefaxiang1 小时前
C语言常见概念(下)
c语言·开发语言
欧阳天风1 小时前
js实现鼠标横向滚动
开发语言·前端·javascript
yue0082 小时前
C# Directory的用法介绍
开发语言·c#
seeyoutlb2 小时前
微服务全局日志处理
java·python·微服务
ada7_2 小时前
LeetCode(python)——148.排序链表
python·算法·leetcode·链表
雨落秋垣2 小时前
手搓 Java 的用户行为跟踪系统
java·开发语言·linq
岁月宁静3 小时前
LangChain + LangGraph 实战:构建生产级多模态 WorkflowAgent 的完整指南
人工智能·python·agent
爱丽_3 小时前
深入理解 Java Socket 编程与线程池:从阻塞 I/O 到高并发处理
java·开发语言