[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
        
相关推荐
Chef_Chen1 分钟前
从0开始学习R语言--Day20-ARIMA与格兰杰因果检验
开发语言·学习·r语言
zh_xuan2 分钟前
c++ std::pair
开发语言·c++
乾巫宇宙国监察特使8 分钟前
Python的设计模式
python·测试
Hockor16 分钟前
写给前端的 Python 教程四(列表/元组)
前端·后端·python
CodeWithMe24 分钟前
【C/C++】EBO空基类优化介绍
开发语言·c++
这里有鱼汤25 分钟前
熟练掌握MACD这8种形态,让你少走三年弯路(附Python量化代码)| 建议收藏
后端·python
404.Not Found34 分钟前
Day46 Python打卡训练营
开发语言·python
love530love36 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
凌辰揽月37 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
海奥华241 分钟前
go中的接口返回设计思想
开发语言·后端·golang