[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
        
相关推荐
vx-程序开发2 分钟前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
charlie1145141919 分钟前
IMX6ULL WM8960 的移植——前置介绍
开发语言·c++·开源项目·嵌入式linux
雪山青木20 分钟前
全国微博签到数据201912-202004
大数据·爬虫·python·数据挖掘·数据分析·新浪微博
迷迭香yy32 分钟前
Python实战:涨停板“假封板”识别系统的工程实现
开发语言·人工智能·python
charlie11451419133 分钟前
Cinux是如何管理进程的 —— 上下文与调度
开发语言·c++·操作系统·开源项目
aqi001 小时前
15天学会AI应用开发(二十)使用LangChain实现RAG检索功能
人工智能·python·ai编程
-银雾鸢尾-1 小时前
C#中的协变和逆变
开发语言·c#
阿米亚波1 小时前
【C++ 异常处理】try-catch
开发语言·c++·笔记·try-catch
本地化文档1 小时前
skbuild-docs-l10n
python·github·gitcode·sphinx