[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
        
相关推荐
henujolly2 分钟前
ethers.js读取合约信息
开发语言·javascript·区块链
Eugene__Chen5 分钟前
Java关键字(曼波版)
java·开发语言
lixin55655622 分钟前
基于深度生成对抗网络的高质量图像生成模型研究与实现
java·人工智能·pytorch·python·深度学习·语言模型
无望__wsk31 分钟前
Python第一次作业
开发语言·python·算法
Word码38 分钟前
[C++语法]-vector(用法详解及实现)
开发语言·c++
代码雕刻家1 小时前
4.3.多线程&JUC-多线程的实现方式
java·开发语言
梦6501 小时前
网络传输七层协议
开发语言·网络·php
南 阳1 小时前
Python从入门到精通day16
开发语言·python·算法
MasonYyp1 小时前
Agno中使用MCP
python
aiguangyuan1 小时前
从零实现循环神经网络:中文情感分析的完整实践指南
人工智能·python·nlp