这里使用了哪种x阶树遍历(深度优先搜索)?

时间:2019-01-20 01:48:18

标签: python python-3.x

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]]

...但是,我不能确切地说出这里使用的是哪种类型的遍历。当我看到像这样的“节点”和“左” /“右”属性的使用时,我认识到按顺序遍历:

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]

1 个答案:

答案 0 :(得分:1)

这是一个预定遍历。这意味着它访问节点的顺序为(根,子节点)。 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)

首先,它访问当前节点并检查是否为解决方案。然后它继续向孩子们前进。预订遍历。