[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
        
相关推荐
csdn2015_14 小时前
MybatisPlus LambdaQueryChainWrapper 联合查询
开发语言·windows·python
骑猪撞地球QAQ14 小时前
Java在导出excel时中添加图片导出
java·开发语言·excel
好家伙VCC14 小时前
# 发散创新:基于 Go 语言打造高性能服务网格的实践与突破在微服务架构
java·python·微服务·架构·golang
悦悦子a啊14 小时前
CSS 知识点
开发语言·前端·css
-To be number.wan14 小时前
Python数据分析:pyecharts可视化
python·信息可视化·数据分析
好家伙VCC14 小时前
# BERT在中文文本分类中的实战优化:从模型微调到部署全流程在自然语言处理(NL
java·python·自然语言处理·分类·bert
海棠AI实验室14 小时前
第五章 指令数据怎么写:从“有用”到“可学”的指令模板库
python·模型训练·私有模型训练
只会写bug的小李子14 小时前
AI Agent动态规划失效处理:多步执行卡壳时,局部修正远比从头重来更高效
java·开发语言
unirst198500714 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
杨超越luckly14 小时前
HTML应用指南:利用GET请求获取中国邮政网点位置信息
前端·python·arcgis·html·php·数据可视化