120.三角形最小路径和(动态规划)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a6aa76e36a906f30c8ec5a1b10f04a91.png)
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle == null || triangle.size() < 1) return 0;
int m = triangle.size();
int n = triangle.get(m - 1).size();
int[] dp = new int[n + 1];
for(int i = m - 1; i >= 0; i--) {
for(int j = 0; j < triangle.get(i).size(); j++) {
dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
}
}
return dp[0];
}
}
129.求根到叶子节点数字之和(递归)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/05a44aa746551814347b04e737f917a5.png)
class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
dfs(root, new StringBuilder());
return res;
}
public void dfs(TreeNode root, StringBuilder sb) {
if(root == null) return;
if(root.left == null && root.right == null) {
sb.append(root.val);
res += Integer.valueOf(sb.toString());
sb.deleteCharAt(sb.length() - 1);
return;
}
sb.append(root.val);
dfs(root.left, sb);
dfs(root.right, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
class Solution {
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
return dfs(root, 0);
}
public int dfs(TreeNode root, int num) {
if(root == null) return 0;
int temp = num * 10 + root.val;
if(root.left == null && root.right == null) return temp;
return dfs(root.left, temp) + dfs(root.right, temp);
}
}