1. 程式人生 > >198. House Robber 強盜搶劫 Java

198. House Robber 強盜搶劫 Java

tps pre nbsp most style ava span lee discus

網址: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;
    }
}

技術分享圖片

198. House Robber 強盜搶劫 Java