Day 25 - Permutations

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~


46. Permutations

Question

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.


Example

Example1

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example2

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example3

Input: nums = [1]
Output: [[1]]

Constraints

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.

解题

题目

首先先简单的翻译一下题目
给一组阵列,回传该阵列的所有排列可能。

Think

作法大致上是这样

  • 用递回的方式做~以[1, 2, 3]当例子
  • for loop 先选出来一个出来1,剩下[2, 3],再继续做递回,一直到进入递回的第一个if长度为0的时候回传ans。

Code

Python

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ans = []
        
        if len(nums) in [0, 1]:
            ans.append(nums)
        
            return ans

        for index in range(len(nums)):
            for remain in self.permute(nums[:index] + nums[index+1:]):
                ans.append([nums[index]] + remain)

        return ans

Result

  • Python

大家明天见/images/emoticon/emoticon29.gif


<<:  [早餐吃到饱-6] JR Inn Sapporo #日本北海道

>>:  DAY 28 Image message(图片讯息)

[Day 26] 快照测试(Snapshot Testing)是什麽?什麽时间适合使用?

快照测试第一时间听起来好像是会「帮我们的画面做一个快照,纪录下来当时的画面」,但这样的说法对也不对...

[Day29] Cost Plaining

终於到了倒数第二篇文章了,今天来介绍云端付费相关的计画,透过一些小技巧,可以减少在云端上的很多开销哦...

Day 8 [Python ML、特徵工程] 基准模型(Baseline Model)

前言 今天开始是新的章节,因此也有新的资料集 Kickstarter Projects 在开始之前要...

愿Alex老师安息,一路好走!

Alex老师是为台湾CISSP资安教育训练开创新局的好老师! 愿Alex老师安息,一路好走! Al...

DAY26 第一个完整程序练习,一台计算机!(一)

今天我们要来做一个专案,我要做一个计算机,以我们所学的来说技术方面很简单,但逻辑方面会比较难,以我来...