[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
        
相关推荐
fie88895 分钟前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
gihigo19987 分钟前
MATLAB中生成混淆矩阵
开发语言·matlab·矩阵
dreams_dream22 分钟前
Flask
后端·python·flask
曾几何时`23 分钟前
C++——this指针
开发语言·c++
小冯的编程学习之路36 分钟前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
mywpython37 分钟前
用Python和Websockets库构建一个高性能、低延迟的实时消息推送服务
python·websocket
ZPC82101 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
一晌小贪欢1 小时前
Python键盘鼠标自动化库详解:从入门到精通
python·自动化·计算机外设·python鼠标·python键盘·python操控鼠标·python操控键盘
穿西装的水獭2 小时前
python将Excel数据写进图片中
开发语言·python·excel
老友@2 小时前
Java Excel 导出:EasyExcel 使用详解
java·开发语言·excel·easyexcel·excel导出