栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

DP DFS EASY 2021.11.12

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DP DFS EASY 2021.11.12

面试题17.16.按摩师

动态规划,关键是列出状态转移表格。

还要想清楚边界值。

27931
cur27111012
max27111112
21453113
cur2166971012
max2266991012
class Solution {
    public int massage(int[] nums) {
        if (nums.length == 0){
            return 0;
        }
        if (nums.length == 1){
            return nums[0];
        }
        int[] max = new int[nums.length];
        int[] ans = new int[nums.length];
        max[0] = nums[0];
        max[1] = Math.max(nums[0], nums[1]);
        ans[0] = nums[0];
        ans[1] = nums[1];
        for (int i = 2; i < nums.length; i++){
            ans[i] = max[i - 2] + nums[i];
            max[i] = Math.max(max[i - 1], ans[i]);
        }
        return max[nums.length - 1];
    }
}

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:35.5 MB, 在所有 Java 提交中击败了89.00%的用户


144. 二叉树的前序遍历

前序遍历:根左右。

class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
        ArrayList res = new ArrayList();
        preorder(root, res);
        return res;
    }

    public void preorder(TreeNode root, List res){
        if (root == null){
            return;
        }
        res.add(root.val);
        preorder(root.left, res);
        preorder(root.right, res);
    }
}

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:36.7 MB, 在所有 Java 提交中击败了53.17%的用户

新知识

//动态数组声明,有括号
ArrayList A = new ArrayList();
//如果函数没有返回值,声明时用void
public void ...
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/490166.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号