choose-> explore-> unchoose paradigm is the key! below is the general pseudo code
来看看例子一:Given a collection of distinct integers, return all possible permutations.
Input: [1,2,3]
Output:
[
[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):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums: #sanity check
return []
res = []
self.helper(nums, res, [])
return res
def helper(self, nums, res, item): #explore
if len(item) == len(nums):
res.append(item[:]) #为什么要item[:]可以去研究研究python的参数传入
return
for num in nums:
if num not in item:
item.append(num) #choose
print item # put a print here just to give a hint of why we need to unchoose,you can see the item list growing and shrinking
self.helper(nums, res, item) #explore recursively
item.pop() #unchoose
再来看个例子:给定掷骰子的次数,再给定目标和,输出所有点数和等于目标和的组合
class Solution(object):
def diceSum(self, num, sum):
res = []
self.helper(num, sum, res, [])
return res
def helper(self, num, sum, res, path):
if num == 0:
if sum == 0:
res.append(path[:]) #path[:]就相当于Java里的new ArrayList(path),新内存
return
return
for i in xrange(1,7):
path.append(i) #choose
self.helper(num-1, sum-i, res, path) #explore
path.pop() #unchoose
上面的程序可以解决问题,可是还不完美,我们可以进行剪枝优化,这里代码就不列出了。