当前位置: 首页 > news >正文

Day31 | 139. 单词拆分、198. 打家劫舍、213. 打家劫舍 II、337. 打家劫舍 III

139. 单词拆分

题目链接:139. 单词拆分 - 力扣(LeetCode)

题目难度:中等

代码:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        HashSet<String> set=new HashSet<>(wordDict);
        boolean[] valid=new boolean[s.length()+1];
        valid[0]=true;
        for(int i=1;i<=s.length();i++){
            for(int j=0;j<i;j++){
                if(set.contains(s.substring(j,i))&&valid[j])
                    valid[i]=true;
            }
        }
        return valid[s.length()];
    }
}

198. 打家劫舍

题目链接:198. 打家劫舍 - 力扣(LeetCode)

题目难度:中等

代码:

class Solution {
    public int rob(int[] nums) {
        if(nums.length==1) return nums[0];
        int[] dp=new int[nums.length];
        dp[0]=nums[0];
        dp[1]=Math.max(nums[0],nums[1]);
        for(int i=2;i<nums.length;i++){
            dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
        }
        return dp[nums.length-1];
    }
}

213. 打家劫舍 II

题目链接:213. 打家劫舍 II - 力扣(LeetCode)

题目难度:中等

代码:

class Solution {
    public int rob(int[] nums) {
        if(nums.length==1) return nums[0];
        int len = nums.length;
        return Math.max(robAction(nums,0,len-1),robAction(nums,1,len));
    }
    public int robAction(int[] nums,int start,int end){
        int x = 0, y = 0, z = 0;
        for (int i = start; i < end; i++) {
            y = z;
            z = Math.max(y, x + nums[i]);
            x = y;
        }
        return z;
    }
}

337. 打家劫舍 III

题目链接:337. 打家劫舍 III - 力扣(LeetCode)

题目难度:中等

代码:

class Solution {
    public int rob(TreeNode root) {
        int[] res=robAction(root);
        return Math.max(res[0],res[1]);
    }

    int[] robAction(TreeNode root){
        int res[]=new int[2];
        if(root==null)
            return res;
        int left[]=robAction(root.left);
        int right[]=robAction(root.right);
        res[0]=Math.max(left[0],left[1])+Math.max(right[0],right[1]);
        res[1]=root.val+left[0]+right[0];
        return res;
    }
}

相关文章:

  • 微前端教程:使用 Single-SPA 构建模块化应用
  • 江科大51单片机笔记【10】DS1302时钟可调时钟(下)
  • 带权重的词典设计
  • 【Godot4.3】Geometry2D总结
  • 基于Vue 3的智能支付二维码弹窗组件设计与实现
  • MySQL事务深度解析:ACID特性、隔离级别与MVCC机制
  • 歌词相关实现
  • Vscode工具开发Vue+ts项目时vue文件ts语法报错-红波浪线等
  • 第n小的质数(信息学奥赛一本通-1099)
  • 【每日学点HarmonyOS Next知识】获取资源问题、软键盘弹起、swiper更新、C给图片设置位图、读取本地Json
  • 为AI聊天工具添加一个知识系统 之142 设计重审 之7 “我I”:mine/own/self
  • 程序化广告行业(9/89):定义、价值与发展脉络全解析
  • 版本控制器Git(3)
  • 微信小程序校园跑腿的设计与实现【lw+源码+部署+视频+讲解】
  • uni-app打包成H5使用相对路径
  • 串口通信函数汇总-ing
  • SpringMVC执行的流程
  • 子网掩码介绍
  • 批量ip反查域名工具
  • 第十八:go 并发 goroutine
  • 重庆荣昌出圈背后:把网络流量变成经济发展的增量
  • 中国一重集团有限公司副总经理陆文俊被查
  • 47本笔记、2341场讲座,一位普通上海老人的阅读史
  • 追光|铁皮房、土操场,这有一座“筑梦”摔跤馆
  • 光大华夏:近代中国私立大学遥不可及的梦想
  • “用鲜血和生命凝结的深厚情谊”——习近平主席署名文章中的中俄友好故事