[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 分钟前
跨境电商AI批量图片翻译工具,视频字幕翻译免费试用
人工智能·python·音视频
开开心心就好4 分钟前
电子教鞭工具支持画框写字插图片功能齐全
android·开发语言·前端·javascript·人工智能·pdf·html
zx_7414848114 分钟前
【Python入门】爬虫实战:Requests + XPath 从基础到实战
开发语言·爬虫·python
高洁0115 分钟前
Teacher Forcing技术解析
人工智能·python·深度学习·transformer·知识图谱
2601_9620652524 分钟前
从零创建一个 Django 项目
后端·python·django
吴声子夜歌27 分钟前
Java——开发中通用的方法和准则(二)
java·开发语言·php
江屿风39 分钟前
C++OJ题经验总结(竞赛)5
开发语言·c++
溪语流沙42 分钟前
【Python项目实战】虚拟环境与依赖管理:venv / pip / requirements.txt实操
开发语言·python·pip
神威难绷泪42 分钟前
Linux应用软件编程:线程分离属性 互斥机制 同步机制 死锁
linux·开发语言·算法·线程
研☆香1 小时前
数组方法 splice讲解 拓展
开发语言·前端·javascript