58/300
全排列 给定一个没有重复数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]好想直接用itertools.permutations() 但估计‘又’不能那么玩儿。。
常规思路:recursion
[1,2,3] 选 [1] 剩下[2,3]
[2,3] 选[2] 剩下[3] [3]返回[3] [2,3] 选[2] 剩下[3] → \to → [2]+[3] = [2,3] :lst = [[2,3]]
[2,3] 选[3] 剩下[2] [2]返回[2] [2,3] 选[3] 剩下[2] → \to → [3]+[2] = [3,2] :lst = [[2,3],[3,2]]
[1,2,3] 选 [1] 剩下[2,3] → \to → [1] + [2,3] = [1,2,3] → \to → [1] + [3,2] = [1,3,2] :lst = [[1,2,3],[1,3,2]]
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if len(nums) <= 1: return [nums] #(list of list) mylist = [] for i, n in enumerate(nums): _part = nums[:i] + nums[i+1:] #another part of the list for m in self.permute(_part): #list in (list of list) mylist.append([n] + m) #list + list return mylist #(list of list)休息日,只刷一道