[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 分钟前
Java 集合常见问题总结(3)
java·开发语言·后端
沐知全栈开发14 分钟前
ionic 对话框:深度解析与最佳实践
开发语言
Jia ming21 分钟前
《智能法官软件项目》—罪名初判模块
python·教学·案例·智能法官
Jia ming37 分钟前
《智能法官软件项目》—法律文书生成模块
python·教学·案例·智能法官软件
曦月逸霜1 小时前
Python数据分析——个人笔记(持续更新中~)
python
海棠AI实验室1 小时前
第六章 从“能用”到“能交付”的关键一刀:偏好对齐(Preference Alignment)数据工程
python·私有模型训练
浅念-1 小时前
C++ string类
开发语言·c++·经验分享·笔记·学习
百锦再1 小时前
Java多线程编程全面解析:从原理到实战
java·开发语言·python·spring·kafka·tomcat·maven
Cosmoshhhyyy1 小时前
《Effective Java》解读第38条:用接口模拟可扩展的枚举
java·开发语言
小冷coding1 小时前
【Java】最新Java高并发高可用平台技术选型指南(思路+全栈路线)
java·开发语言