Description,
Given a collection of distinct numbers, return all possible permutations.
the leetcode link
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Recursive solution
The trick is to “fix” each number in the list, then recursively doing so to the rest of the list.
When it reaches the last one, just return it.
Note: to make the code looks more concise, I let the list goes empty, instead terminate the recursion when the list reaches the length of 1.
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
ret = []
for i in xrange(len(nums)):
for tmpList in self.permute(nums[:i] + nums[i+1:]):
ret.append([nums[i]] + tmpList)
return ret
Runtime: 65ms