秋招面/笔试题目集合——04

第一题

完全背包问题(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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值