[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
        
相关推荐
成长痕迹6 分钟前
【Python与Matlab数据分析对比】
python·matlab·数据分析
11年老程序猿在线搬砖10 分钟前
如何搭建自己的量化交易平台
大数据·人工智能·python·自动交易·量化交易系统
消失的旧时光-194319 分钟前
Kotlin 协程最佳实践:用 CoroutineScope + SupervisorJob 替代 Timer,实现优雅周期任务调度
android·开发语言·kotlin
错把套路当深情26 分钟前
Kotlin保留小数位的三种方法
开发语言·python·kotlin
错把套路当深情26 分钟前
Kotlin基础类型扩展函数使用指南
python·微信·kotlin
千里码aicood30 分钟前
python+vue旅游购票管理系统设计(源码+文档+调试+基础修改+答疑)
vue.js·python·旅游
B站_计算机毕业设计之家37 分钟前
python电商商品评论数据分析可视化系统 爬虫 数据采集 Flask框架 NLP情感分析 LDA主题分析 Bayes评论分类(源码) ✅
大数据·hadoop·爬虫·python·算法·数据分析·1024程序员节
写代码的安徒生41 分钟前
调用 Google Veo 3.1 API 批量制作电商产品 UGC 视频
python·音视频
赵谨言2 小时前
基于Python Web的大数据系统监控平台的设计与实现
大数据·开发语言·经验分享·python
专注前端30年2 小时前
Vue2 中 v-if 与 v-show 深度对比及实战指南
开发语言·前端·vue