zoukankan      html  css  js  c++  java
  • Path Sum II

    Path Sum II

    问题:

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    思路:

      dfs + 回溯

    我的代码:

    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root == null) return rst;
            List<Integer> list = new ArrayList<Integer>();
            helper(root, sum, list);
            return rst;
        }
        private List<List<Integer>> rst = new ArrayList<List<Integer>>();
        public void helper(TreeNode root, int sum, List<Integer> list)
        {
            if(root == null)    return;
            if(root.left == null && root.right == null)
            {
                if(sum == root.val)
                {
                    list.add(root.val);
                    rst.add(new ArrayList(list));
                    list.remove(list.size() - 1);
                }
                return;
            }
            list.add(root.val);
            helper(root.left, sum - root.val, list);
            helper(root.right, sum - root.val, list);
            list.remove(list.size() - 1);
        }
    }
    View Code

    学习之处:

    • 对于含有List的Dfs一定要记在心里面List需要remove,是地址,是地址,是地址!!!!需要回溯,否则会有冗余。
  • 相关阅读:
    局部组件
    flex布局
    Websocket
    关于Javascript夜里再来分析下
    go build、go mod等命令
    websocket
    FileSystemWatcher使用
    DataGridView双缓冲
    C#读INI文件
    c 通过 COM接口调用 Excel.Application 问题终于解决
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4334397.html
Copyright © 2011-2022 走看看