[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
        
相关推荐
C+-C资深大佬6 分钟前
C++数据类型
开发语言·c++·算法
ID_1800790547311 分钟前
日本乐天商品详情API接口的请求构造与参数说明
开发语言·python·pandas
派大鑫wink18 分钟前
【Day34】Servlet 进阶:会话管理(Cookie vs Session)
java·开发语言·学习方法
多米Domi01122 分钟前
0x3f 第35天 电脑硬盘坏了 +二叉树直径,将有序数组转换为二叉搜索树
java·数据结构·python·算法·leetcode·链表
猫天意32 分钟前
【深度学习小课堂】| torch | 升维打击还是原位拼接?深度解码 PyTorch 中 stack 与 cat 的几何奥义
开发语言·人工智能·pytorch·深度学习·神经网络·yolo·机器学习
crossaspeed1 小时前
Java-线程池(八股)
java·开发语言
UR的出不克1 小时前
使用 Python 爬取 Bilibili 弹幕数据并导出 Excel
java·python·excel
niaiheni1 小时前
PHP文件包含
开发语言·php
初次见面我叫泰隆1 小时前
Qt——1、初识Qt
开发语言·c++·qt
Arms2062 小时前
python时区库学习
开发语言·python·学习