前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >leetcode 198 House Robber

leetcode 198 House Robber

作者头像
流川疯
发布2019-01-18 16:15:51
发布2019-01-18 16:15:51
46900
代码可运行
举报
运行总次数: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.

the objective function is basically:

dp(i) = max(dp[i-2] + num[i], dp[i-1]),

this means the current max is the max of the position i-2 plus the current num[i], or the max of the previous one i-1 (cannot including num[i] with i-1 position, otherwise it will trigger the alarm)

我的解决方案:

代码语言:javascript
代码运行次数:0
运行
复制
class Solution {
public:
    int rob(vector<int>& nums)
    {
        if(nums.empty())return 0;

        int length = nums.size();
        vector<int> dp(length,0);

        dp[0] = nums[0];
        dp[1] = max(nums[0],nums[1]);

        for(int i =2; i< length; ++i)
        {
            dp[i] = max(dp[i-2]+nums[i],dp[i-1]);
        }

        return dp[length-1];

    }
};

c语言解决方案:

代码语言:javascript
代码运行次数:0
运行
复制
#define max(a, b) ((a)>(b)?(a):(b))
int rob(int num[], int n) {
    int a = 0;
    int b = 0;

    for (int i=0; i<n; i++)
    {
        if (i%2==0)
        {
            a = max(a+num[i], b);
        }
        else
        {
            b = max(a, b+num[i]);
        }
    }

    return max(a, b);
}

python解决方案:

代码语言:javascript
代码运行次数:0
运行
复制
class Solution:
    # @param num, a list of integer
    # @return an integer
    def rob(self, num):
        # DP O(n) time, O(1) space
        # ik: max include house k
        # ek: max exclude house k, (Note: ek is also the maximum for house 1,...,k-1)
        # i[k+1]: num[k] + ek #can't include house k
        # e[k+1]: max(ik, ek) # can either include house k or exclude house k
        i, e = 0, 0
        for n in num: #from k-1 to k
            i, e = n+e, max(i,e)
        return max(i,e)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年04月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档