Permutations
Description:
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
算法分析:解决这个问题,很容易想到树,一层层地生成。
因此我们可以考虑用递归的方式。
代码如下:
__author__ = 'andy'
class Solution(object):
def permute(self, nums):
self.result = []
subList = []
self.cal(nums,subList)
return self.result
def cal(self,nums,subList):
#如果子链表跟原链表等长,则加到结果中
if len(nums)==len(subList):
self.result.append(subList[:])
#用递归的方式,得出组合
for a in nums:
if a in subList:
continue
subList.append(a)
self.cal(nums,subList)
subList.remove(a)
case = Solution()
nums =[1,2,3]
print(case.permute(nums))
结果: