大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Input: nums = [1]
Output: [[1]]
1 <= nums.length <= 6
-10 <= nums[i] <= 10
首先先簡單的翻譯一下題目
給一組陣列,回傳該陣列的所有排列可能。
作法大致上是這樣
[1, 2, 3]
當例子1
,剩下[2, 3]
,再繼續做遞迴,一直到進入遞迴的第一個if
長度為0的時候回傳ans。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
大家明天見