赞
踩
list的add方法底层实现原理是基于指针,list对象指向添加元素的内存地址,对应内存地址元素发生改变,它的值也会发生改变。
在下面的代码中:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList(); if( root == null ) return res; List<Integer> path = new ArrayList(); getSum(root, targetSum, res, path, 0); return res; } public void getSum(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path, int sum) { sum += root.val; path.add(root.val); if( (root.left == null) && (root.right == null) ) { if( sum == targetSum ) { // System.out.println(path.toString()); // System.out.println(path.size()); // List<Integer> tmp = new ArrayList(); // for(Integer p:path) { // tmp.add(p); // } res.add(path); } return; // path.remove(path.size()-1); } if(root.left != null ) { getSum(root.left, targetSum, res, path, sum); path.remove(path.size()-1); } if(root.right != null ) { getSum(root.right, targetSum, res, path, sum); path.remove(path.size()-1); } } }
path发生改变,对应的res也会改变。
而下面的代码中,res会保留原本值,根本原因是,用了新的内存来保存相应的值。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList(); if( root == null ) return res; List<Integer> path = new ArrayList(); getSum(root, targetSum, res, path, 0); return res; } public void getSum(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path, int sum) { sum += root.val; path.add(root.val); if( (root.left == null) && (root.right == null) ) { if( sum == targetSum ) { // System.out.println(path.toString()); // System.out.println(path.size()); List<Integer> tmp = new ArrayList(); for(Integer p:path) { tmp.add(p); } res.add(tmp); } return; // path.remove(path.size()-1); } if(root.left != null ) { getSum(root.left, targetSum, res, path, sum); path.remove(path.size()-1); } if(root.right != null ) { getSum(root.right, targetSum, res, path, sum); path.remove(path.size()-1); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。