Python 这里使用的是哪种x阶树遍历(深度优先搜索)?
使用某种深度优先遍历快速求解,因为它涉及子集:Python 这里使用的是哪种x阶树遍历(深度优先搜索)?,python,python-3.x,Python,Python 3.x,使用某种深度优先遍历快速求解,因为它涉及子集: class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ results = [] if c
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)
…但在此解决方案中,对节点和左/右子节点的引用不明确。在本例中,“节点”是候选者列表的子集,但这是按顺序遍历的吗?还是预订前/预订后
*更新:我在递归
的顶部打印了组合
,得到了以下信息:
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]
这是一个预顺序遍历。这意味着它访问节点的顺序是(根节点、子节点)。recurse
函数本质上是以下函数的美化版本:
def depth_first_search(state):
if state is solution:
results.append(state)
for next_state in next_possible_states:
if next_state is valid:
depth_first_search(next_state)
首先,它访问当前节点并检查它是否是解决方案。然后是孩子们。预序遍历。我看不出有任何理由相信这是递归树遍历,而不是简单的递归。@coldspeed-通过树遍历解释的这个问题的java版本:您的伪代码有意义。你能看一下我的问题的更新,看看打印的结果是否与你描述的相符吗?是的。从根开始([]
),然后转到根的第一个子级,检查它是否是解决方案,然后移动到子级的子级。一旦你点击[2,2,3]
,你就没有有效的孩子可以访问了。你又回到了根的另一个孩子。这种情况持续不断。所有这些都是拜访父母,然后是孩子。