This leetcode question
使用深度优先遍历快速解决,因为它涉及子集:
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
results = []
if candidates == None or len(candidates) == 0:
return results
candidates = sorted(candidates)
combination = []
self.recurse(results, combination, candidates, target, 0)
return results
def recurse(self, results, combination, candidates, target, startIndex):
'''
walk the tree, looking for a combination of candidates that sum to target
'''
print("combination is : " + str(combination))
if target == 0:
# must add a copy of the list, not the list itself
results.append(combination[:])
return;
for i in range(startIndex, len(candidates)):
if candidates[i] > target:
break
combination.append(candidates[i])
self.recurse(results, combination, candidates, target - candidates[i], i)
combination.remove(combination[len(combination) - 1])
s = Solution()
results = s.combinationSum([2,6,3,7], 7)
print(results)
assert results == [[2, 2, 3], [7]]
…但是,我不能确切地知道这里使用的是哪种类型的遍历。当我看到“nodes”和“left”/“right”属性的用法时,我按顺序遍历:
def inorder(node):
if node == None: return
inorder(node.left)
do_something_with_node(node)
inorder(node.right)
…但是在这个解决方案中,对节点和左/右子节点的引用并不明确。”节点”是
candidates
在本例中列出,但这是按顺序遍历的吗?还是预订单/后订单?
*更新:我打印了
combination
在顶部
recurse
得到这个:
combination is : []
combination is : [2]
combination is : [2, 2]
combination is : [2, 2, 2]
combination is : [2, 2, 3]
combination is : [2, 3]
combination is : [3]
combination is : [3, 3]
combination is : [6]
combination is : [7]