zoukankan      html  css  js  c++  java
  • [leetcode] 113. 路径总和 II

    113. 路径总和 II

    这题跟上个题的区别112. 路径总和,需要保存下路径,且有可能出现多条路径。

    在前一个题的基础上加上回溯即可

    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> ansList = new ArrayList<>();
            if (root == null) return ansList;
            List<Integer> curList = new ArrayList<>();
    
            findPath(root, sum, curList, ansList);
    
            return ansList;
        }
    
        private void findPath(TreeNode root, int sum, List<Integer> curList, List<List<Integer>> ansList) {
            if (root == null) return;
            curList.add(root.val);
            if (root.left == null && root.right == null && sum == root.val) {
                List<Integer> tmp = new ArrayList<>(curList);
                ansList.add(tmp);
            } else {
                findPath(root.left, sum - root.val, curList, ansList);
                findPath(root.right, sum - root.val, curList, ansList);
            }
            curList.remove(curList.size() - 1);
        }
    }
    
    
  • 相关阅读:
    网络编程TCP
    collections模块
    异常处理
    hashlib模块
    configparse模块
    logging模块
    序列化模块
    os模块
    时间模块
    random模块
  • 原文地址:https://www.cnblogs.com/acbingo/p/9918325.html
Copyright © 2011-2022 走看看