[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
        
相关推荐
CLX050534 分钟前
如何安装Oracle 12c Cloud Control_OMS服务端组件与Agent部署
jvm·数据库·python
大卡片42 分钟前
C++的基础知识点
开发语言·c++
郑同学的笔记1 小时前
【Qt教程29】Qt5和Qt6版本对比
开发语言·qt
基德爆肝c语言1 小时前
Qt 主窗口全家桶:菜单栏、工具栏、状态栏与对话框完全指南
开发语言·qt
老纪1 小时前
SQL中如何查找特定的空值行:WHERE IS NULL深度解析
jvm·数据库·python
噜噜噜阿鲁~2 小时前
python学习笔记 | 10.0、面向对象编程
笔记·python·学习
weixin199701080162 小时前
[特殊字符] RESTful API 接口规范详解:构建高效、可扩展的 Web 服务(附 Python 源码)
前端·python·restful
2301_781571422 小时前
mysql数据库响应缓慢如何排查_使用EXPLAIN分析执行计划
jvm·数据库·python
彳亍1012 小时前
实现倒计时数字在到达1后自动隐藏(2为最后可见数字),同时继续运行至-1再终止
jvm·数据库·python
X56613 小时前
CSS如何处理SSR中CSS引入_在服务端渲染时提取关键CSS
jvm·数据库·python