Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
I can not think of how to solve this problem in a elegant way. I know it needs to be done recursively, while... it will for sure takes me a lot of time to consider. Anyway, this is really a good piece of code!
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
length = len(num)
if length == 0:
return []
elif length == 1:
return [num]
result = []
for index in range(length):
for rest_perm in self.permute(num[0: index] + num[index + 1 :]):
result.append([num[index]] + rest_perm)
return result