回溯之Leetcode 113 路径总和 II

35 阅读1分钟

如果人生能回溯

人生总是充满选择,而一旦选错,往往没有后悔药可吃。就像电影《黑客帝国》中的情节,主角必须在两种药丸中选择一种,无法回头。后来,我学到了一种叫做回溯的算法,它允许你在尝试中不断调整,直到找到最佳路径。这让我不禁思考,如果人生也能像回溯算法一样,能够不断试错并探索所有可能性,那该多好!所以,少年,不,应该是中年boy,让我们一起来看看如何实现这种思路吧。

回溯的套路

回溯的套路很简单,三步:

  1. 添加选择
  2. 递归
  3. 撤销选择

是不是有点像把大象放冰箱,一共分几步呢?手动狗头。

Leetcode 113 路径总和 II

注意path不是一个栈

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> path = new ArrayDeque<>();

        dfs(res, path, root, targetSum);
        return res;
    }

    private void dfs(List<List<Integer>> res, Deque<Integer> path, TreeNode node, int sum ){
        if(node == null ){
            return;
        }
        path.add(node.val);//1.添加选择
        sum -= node.val;
        if(node.left == null && node.right == null && sum == 0){
            res.add(new ArrayList<>(path));
        }else{//2.递归
            dfs(res, path, node.left, sum);
            dfs(res, path, node.right, sum);
        }

        path.removeLast();//3.撤销选择

    }
}