[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
        
相关推荐
W23035765733 分钟前
【改进版】C++ 固定线程池实现:基于调用者运行的拒绝策略优化
开发语言·c++·线程池
21439653 分钟前
mysql如何处理不走索引的OR查询_使用UNION ALL优化重写
jvm·数据库·python
2301_813599556 分钟前
如何在网页中完整显示数组内所有对象的全部属性
jvm·数据库·python
解救女汉子9 分钟前
如何分析Data Guard的网络瓶颈_Bandwidth与Redo传输速率的计算公式
jvm·数据库·python
m0_7436239214 分钟前
Golang怎么做数据库事务_Golang数据库事务教程【技巧】
jvm·数据库·python
千寻girling14 分钟前
被内推的面试 , 第一次
java·前端·python·面试·职场和发展·typescript·node.js
qq_3300379916 分钟前
模型持久化不会提升准确率——揭秘机器学习中常见的评估误区
jvm·数据库·python
qq_4240985616 分钟前
CSS如何实现背景平铺与拉伸控制_使用background-repeat属性
jvm·数据库·python
AC赳赳老秦20 分钟前
程序员面试:OpenClaw生成面试题、模拟面试,高效备战面试
人工智能·python·机器学习·面试·职场和发展·deepseek·openclaw
qq_4138474021 分钟前
html标签如何正确闭合_self-closing标签注意事项【介绍】
jvm·数据库·python