Given a collection of distinct 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], [3,2,1] ]即,给定一个列表(不重复),返回这个列表所有元素的排列组合。
class Solution(object):
def permute(self, nums):
res = [] #res 用于记录并返回所有排列组合。
self.excute(nums,[],res)
return res
def excute(self,nums,path,res): #path用于存放经过的元素
if not nums:
res.append(path)
for i in xrange(len(nums)):
self.excute(nums[:i]+nums[i+1:],path+[nums[i]],res) #每经过一个元素,将其从nums中取出,放入path,当nums为空时,就完成一个排列组合。