[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
        
相关推荐
m0_726365834 分钟前
哈希分分预测系统 打造自适应趋势分析「Python+DeepSeek+PyQt5」
python·qt·哈希算法
lsx2024068 分钟前
《Foundation 下拉菜单》
开发语言
期待のcode12 分钟前
认识Java虚拟机
java·开发语言·jvm
vyuvyucd14 分钟前
Qwen-1.8B-Chat昇腾Atlas800TA2部署实战
python
raining_peidx15 分钟前
xxljob源码
java·开发语言
肥猪猪爸16 分钟前
双重检查锁(DCL)与 volatile 的关键作用
java·开发语言·单例模式
轻竹办公PPT20 分钟前
2026 年工作计划 PPT 内容拆解,对比不同 AI 生成思路
人工智能·python·powerpoint
yaoxin52112325 分钟前
289. Java Stream API - 从字符串的字符创建 Stream
java·开发语言
癫狂的兔子32 分钟前
【Python】【Flask】抽奖功能
开发语言·python·flask
你怎么知道我是队长34 分钟前
C语言---无名位域
c语言·开发语言