[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
        
相关推荐
京师20万禁军教头10 分钟前
39面向对象(高级)-设计模式
java·开发语言·设计模式
2601_9623815812 分钟前
ArcGIS+Python+AI赋能高标准农田建设项目审计提质增效
python·arcgis·ai·高标准农田审计·大数据审计
rust&python24 分钟前
课程表的归一化处理
python·程序人生·信息可视化
白山编程大哥40 分钟前
Java 迭代器接口详解:从 Iterator 到 ListIterator 的完整指南
java·开发语言·windows
见叶之秋44 分钟前
【C++】String类的使用(含模拟实现)
java·开发语言·c++
想吃火锅10051 小时前
【leetcode】42.接雨水js
开发语言·javascript·ecmascript
2601_962099081 小时前
replit如何运行python
python·代码编辑器·编程环境·在线ide·replit
头发够用的程序员1 小时前
别被 TOPS 参数迷惑:手把手推导边缘 GPU 整型算力
人工智能·python·ubuntu·计算机视觉·硬件架构·边缘计算
TechWayfarer1 小时前
做IP归属地查询时总是查不准?IP纯净度检测实战:从“查归属地“到识别“脏IP“的四个维度
服务器·网络·python·tcp/ip·安全·web安全
小溪学编程2 小时前
Java InputStream 详解:从基础到实战
java·python·php