y*******d 发帖数: 1674 | 1 just started leetcode practice.
has a question about #113:
public class Solution {
public List> pathSum(TreeNode root, int sum) {
List> all = new ArrayList();
findPathSum(root, sum, all, new ArrayList());
return all;
}
private void findPathSum(TreeNode node, int sum, List>
result, List l) {
if (node == null) {
return;
}
l.add(node.val);
if (node.left == null && node.right == null && node.val == sum) {
// has to make a copy, otherwise the content may be changed
ArrayList curPath = new ArrayList(l);
result.add(curPath);
}
findPathSum(node.left, sum - node.val, result, l);
findPathSum(node.right, sum - node.val, result, l);
l.remove(l.size() - 1);
}
}
why is l.remove(l.size() - 1);? | c********t 发帖数: 5706 | 2 backtracking, it removes node value from list
【在 y*******d 的大作中提到】 : just started leetcode practice. : has a question about #113: : public class Solution { : public List> pathSum(TreeNode root, int sum) { : List> all = new ArrayList(); : findPathSum(root, sum, all, new ArrayList()); : return all; : } : : private void findPathSum(TreeNode node, int sum, List>
| s**********g 发帖数: 14942 | 3 backtracking一般都要repair
不然下一个尝试怎么做
这个就是repair
【在 y*******d 的大作中提到】 : just started leetcode practice. : has a question about #113: : public class Solution { : public List> pathSum(TreeNode root, int sum) { : List> all = new ArrayList(); : findPathSum(root, sum, all, new ArrayList()); : return all; : } : : private void findPathSum(TreeNode node, int sum, List>
|
|