[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
        
相关推荐
xyq2024几秒前
组合实体模式
开发语言
来自远方的老作者3 分钟前
第7章 运算符-7.2 赋值运算符
开发语言·数据结构·python·赋值运算符
A.A呐4 分钟前
【C++第二十四章】异常
开发语言·c++
常利兵18 分钟前
解锁Kotlin:数据类与密封类的奇妙之旅
android·开发语言·kotlin
来自远方的老作者20 分钟前
第7章 运算符-7.1 算术运算符
开发语言·数据结构·python·算法·算术运算符
tq6J5Yg1424 分钟前
windows10本地部署openclaw
前端·python
MwEUwQ3Gx28 分钟前
PHP 异步与多线程 从 TrueAsync 展望未来
开发语言·php
pl4H522a642 分钟前
Python 高效实现 Excel 转 TXT 文本
java·python·excel
数据知道1 小时前
claw-code 源码详细分析:Compaction 前置课——上下文压缩在接口层要预留哪些旋钮,避免后期全局返工?
python·ai·claude code
不会写DN1 小时前
Go中如何跨语言实现传输? - GRPC
开发语言·qt·golang