第一题
完全背包问题(01背包问题的扩展版)
public class 第一题04 {
public static void main(String[] args) {
int[] cost = {13,17,19,14,6,16};
int[] value = {189,360,870,184,298,242};
int[][] res = dp(cost, value, 13);
System.out.println(res);
}
public static int[][] dp(int[] cost,int[] value,int m){
int n = cost.length;
int[][] dp = new int[n][m + 1];
for (int i = 0;i < n;i++){
for (int j = 1;j <= m;j++){
dp[i][j] = -1;
}
}
for (int i = 1;cost[0] * i <= m;i++){
dp[0][cost[0] * i] = value[0] * i;
}
for (int i = 1;i < n;i++){
for (int j = 1;j <= m;j++){
dp[i][j] = dp[i - 1][j];
if (j - cost[i] >= 0 && dp[i][j - cost[i]] != -1){
dp[i][j] = Math.max(dp[i][j],dp[i][j - cost[i]] + value[i]);
}
}
}
return dp;
}
}
第二题
leetcode543. 二叉树的直径
思路:二叉树的递归套路
public class 第二题04 {
public static 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;
}
}
public static class Info{
public int maxDistance;
public int height;
public Info(int maxDistance,int height){
this.maxDistance = maxDistance;
this.height = height;
}
}
public static int diameterOfBinaryTree(TreeNode root) {
return process(root).maxDistance;
}
public static Info process(TreeNode root){
if (root == null){
return new Info(0,0);
}
Info left = process(root.left);
Info right = process(root.right);
int maxDistance = Math.max(left.maxDistance, right.maxDistance);
maxDistance = Math.max(maxDistance, left.height + right.height);
return new Info(maxDistance,Math.max(left.height, right.height) + 1);
}
}