[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
        
相关推荐
小小测试开发4 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想4 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波5 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)5 小时前
【无标题】
开发语言·c#
copyer_xyf5 小时前
Python 异常处理
前端·后端·python
XBodhi.6 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧6 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy6 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.6 小时前
【01】Python 机器学习
开发语言·python
为爱停留6 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python