• 198. House Robber 强盗* Java


    网址:https://leetcode.com/problems/house-robber/

    参考:https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems.

    容易得出转移方程,然后要考虑各种极端情况。

    class Solution {
        public int rob(int[] nums) {
            int[] dp = new int[nums.length];
            if(nums.length == 0)
                return 0;
            else
                if(nums.length == 1)
                    return nums[0];
            else
            {
                if(nums.length == 2)
                {
                    return Math.max(nums[0], nums[1]);
                }
                else
                {
                    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], nums[i] + dp[i-2]);
                    }
                    return dp[nums.length-1];
                }
            }
            
        }
    }

    这么做代码显得稍微繁琐,并且可以把dp数组简化为3个不断更新的变量!

    class Solution {
        public int rob(int[] nums) {
            int pre1 = 0;
            int pre2 = 0;
            int temp = 0;
            
            for(int num : nums)
            {
                temp = Math.max(num + pre2, pre1);
                pre2 = pre1;
                pre1 = temp;
            }
            return temp;
        }
    }

  • 相关阅读:
    注释
    Java三种嵌入jsp的方法
    JSP page指令
    Web应用的目录结构
    Tomcat安装和配置
    动态网页和静态网页的区别
    B/S架构与C/S架构的区别
    URL
    常用SQL查询语句
    SQL--Delete语句
  • 原文地址:https://www.cnblogs.com/tornado549/p/10861187.html
Copyright © 2020-2023  润新知