Leetcode House Robber

题目地址:https://leetcode.com/problems/house-robber/

解析:

此问题采用动态规划,根据题意,到达第i个房子最大收益应该为第i-2个房子最大收益加上第i个房子钱数与到达第i-1个房子最大收益两者的最大值。

题目答案:

public class Solution {
    public int rob(int[] num) {
        if(num == null || num.length == 0){
            return 0;
        }
        
        if(num.length == 1)
            return num[0];
            
        int[] ret = new int[num.length+1];
        ret[0] = 0;
        ret[1] = num[0];
        
        for(int i = 2;i<=num.length;i++){
            ret[i] = Math.max(ret[i-2] + num[i-1],ret[i-1]);
        }
        return ret[num.length];
    }
}

 

posted @ 2015-04-08 14:26  buptubuntu  阅读(102)  评论(0)    收藏  举报