[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
        
相关推荐
站大爷IP12 分钟前
Python中None与NoneType的真相:从单例对象到类型系统的深度解析
python
秋难降12 分钟前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
站大爷IP23 分钟前
Python新手踩坑实录:这些错误你可能正在犯
python
我星期八休息28 分钟前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python
深盾安全38 分钟前
uv,下一代Python包管理工具
python
老虎062740 分钟前
JavaWeb前端02(JavaScript)
开发语言·前端·javascript
Python私教1 小时前
YggJS RLogin暗黑霓虹主题登录注册页面 版本:v0.1.1
开发语言·javascript·ecmascript
山烛1 小时前
OpenCV 图像处理基础操作指南(二)
人工智能·python·opencv·计算机视觉
carver w1 小时前
MFC,C++,海康SDK,回调,轮询
开发语言·c++·mfc
跟橙姐学代码2 小时前
学Python,先把这“三板斧”练到炉火纯青!(零基础也能看懂)
前端·python