[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
        
相关推荐
CoderYanger几秒前
视频切割脚本(Python版)
linux·开发语言·windows·后端·python·程序人生·职场和发展
辞旧 lekkk几秒前
CMake工程指南(一)
linux·运维·服务器·开发语言·qt·学习·萌新
迷途呀4 分钟前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
想会飞的蒲公英9 分钟前
逻辑回归为什么叫回归,却用来做分类
人工智能·python·分类·回归·逻辑回归
小七在进步17 分钟前
数据结构:用栈实现队列
开发语言·数据结构
KaMeidebaby18 分钟前
卡梅德生物技术快报|噬菌体筛选:噬菌体筛选工程化优化方案:基于侵染全链条参数调控与水环境应用验证
java·开发语言·人工智能·机器学习·spark
geovindu19 分钟前
go: Floyd-Warshall Algorithms
开发语言·后端·算法·golang
CoderYanger23 分钟前
视频裁剪+缩放+自动添加水印脚本(Python版)
开发语言·后端·python·程序人生·职场和发展·音视频·学习方法
霍格沃兹测试开发学社测试人社区31 分钟前
Node.js 浏览器引擎 + Python 大脑:Playwright 混合架构爬虫系统深度解析
python·架构·node.js
酷酷的身影33 分钟前
Managers/APConfigManager.cs
开发语言·ui·c#