难度: Medium
原题连接
内容描述
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路 1 - 时间复杂度: O(N!)- 空间复杂度: O(N)******
每次取一个作为prefix, 剩下的继续做permutation,然后连接起来加入res中
beats 87.18%
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
res = []
for i in range(len(nums)):
prefix = nums[i]
rest = nums[:i] + nums[i+1:]
for j in self.permute(rest):
res.append([prefix]+j)
return res