• 113 路径之和II


    回溯,全局变量

    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<List<Integer>> res  = new ArrayList<>();
    
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root == null){
                return res;
            }
    
            helper(root, sum, new ArrayList<>());
            return res;
        }
    
        public void helper(TreeNode root, int sum, List<Integer> cur){
            if(root.left == null && root.right == null){
                if(sum == root.val){
                    cur.add(root.val);
                    res.add(new ArrayList<>(cur));
                    cur.remove(cur.size() - 1);
                }
            }
            else{
                cur.add(root.val);
                if(root.left != null){
                    helper(root.left, sum - root.val, cur);
                }
                if(root.right != null){
                    helper(root.right, sum - root.val, cur);
                }
            cur.remove(cur.size() - 1);
    
            }
        }
    }
    
  • 相关阅读:
    CGCDSSQ
    100200H
    斗地主
    借教室
    bzoj 3743
    17B
    能量项链
    589
    16-求连续数组和最大
    15-幸运数组4、7
  • 原文地址:https://www.cnblogs.com/realzhaijiayu/p/13568622.html
Copyright © 2020-2023  润新知