码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】House Robber (middle)

时间:2015-04-16 23:30:36      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

思路:开始写了个递归超时了。反应了好久才反应过来要用动态规划。

递归代码:

int rob(vector<int> &num) {
        return robsub(num, 0, num.size());
    }
    int robsub(vector<int> &num, int s, int e)
    {
        if(s == e) return 0;
        if(e - s == 1) return num[s];
        return max(robsub(num, s + 1, e), num[s] + ((e - s >= 3) ? robsub(num, s + 2, e) : 0));
    }

动态规划:

int rob2(vector<int> &num) {
        vector<int> dp(num.size() + 1, 0); //截止到num[i] - 1时的最大值
        int ans = 0;
        for(int i = 1; i <= num.size(); i++)
        {
            dp[i] = num[i - 1] + max(((i - 2) >= 0 ? dp[i - 2] : 0), ((i - 3) >= 0 ? dp[i - 3] : 0));
            ans = (ans > dp[i]) ? ans : dp[i];
        }
        return ans;
    }

 

我的动态规划代码用的空间太多了,其实只要两个变量记录一下前面的就好。

public class Solution {
    public int rob(int[] num) {
        int i = 0;
        int e = 0;
        for (int k = 0; k<num.length; k++) {
            int tmp = i;
            i = num[k] + e;
            e = Math.max(tmp, e);
        }
        return Math.max(i,e);
    }
}

 

【leetcode】House Robber (middle)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4433519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!