1. 程式人生 > >慢慢學 動態規劃

慢慢學 動態規劃

多做幾道題來理解動態規劃吧。畢竟程式碼寫出來才能算是真正理解了。

A、leetcode 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.

1、原問題可以分解為子問題,子問題與原問題類似,僅僅規模變小。

2、確定狀態

3、確定邊界條件

4、確定狀態轉移方程

we can figure out the SubProblem to find out the maximun of (dp[i-1], dp[i-2]+num[i]). if we have 3 nums, [1,4,2], then we just compare (dp[0]+num[2] , dp[1]) which comes to the answer.

dp[i] = Math.max(dp[i-2]+nums[i], dp[i-1]);

public class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if(n == 0) return 0;
        if(n ==1) return nums[0];
        int[] dp = new int[n];
        dp[0] = nums[0];
        dp[1] = Math.max(dp[0],nums[1]);//確定邊界條件
        int max= dp[1];
        for(int i = 2; i<n;i++){  //確定狀態轉移方程
            dp[i] = Math.max(dp[i-2]+nums[i], dp[i-1]);
            max = Math.max(max,dp[i]);
        }
        return max;
    }
}