198. House Robber (DP)簡答的動態規劃問題Java

198. House Robber

題目

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

題意

你是一個專業的強盜,你計劃在一條路上搶劫房屋。每一個房屋藏着一些錢。因爲相鄰房屋之間有安全系統相連,這個安全系統又與警察相連,所以你不能搶劫相鄰的房屋在同一個晚上。
給你一列非負整數代表每一個房屋的藏的錢數,求出在沒有驚擾警察的情況下,能搶劫到的最多的錢數。

解題思路

這是一道類似於上樓梯的動態規劃問題,我們很容易知道當房屋數量只有1或者2時的最優情況。因此可以用遞歸的思想,因爲當n>2n>2時,第n種情況的最優解只與第D(n1)D(n-1)D(n2)+f(n)D(n-2)+f(n)時的最大值有關,f(n)f(n)爲第nn個房的金幣。終止條件就是到遞歸到房屋數爲1或者0的時候。因此很容易寫出遞歸代碼。

Java代碼

class Solution {
        public int rob(int[] nums) {
        if(nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        int n = nums.length;
        
        int[] dp = new int[n + 1];
        dp[1] = nums[0];
        dp[2] = Math.max(nums[0], nums[1]);
        
        for(int i = 3; i <= n; i++){
            dp[i] = Math.max(nums[i - 1] + dp[i - 2], dp[i - 1]);
        }
        
        return dp[n];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章