leetcode 解題 給定一個沒有重複數字的序列,返回其所有可能的全排列。
給定一個沒有重複數字的序列,返回其所有可能的全排列。
示例:
輸入: [1,2,3] 輸出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
groups = []
import copy
def getAllGroups(groups, nums):
if(not nums):
return groups
element = nums[0]
if(not groups):
groups.append([element])
nums = nums[1:]
return getAllGroups(groups, nums)
else:
newGroups = []
for group in groups:
for i in range(len(group) + 1):
tempGroup = copy.deepcopy(group)
tempGroup.insert(i, element)
newGroups.append(tempGroup)
nums = nums[1:]
return getAllGroups(newGroups, nums)
return getAllGroups(groups, nums)