天天看点

慢慢学 动态规划

多做几道题来理解动态规划吧。毕竟代码写出来才能算是真正理解了。

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;
    }
}