zoukankan      html  css  js  c++  java
  • 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.

    int rob(vector<int> &num) {
        if(num.size()==0)
            return 0;
        if(num.size()==1)
            return num[0];
        cout<<num.size()<<endl;
        vector<int> total(num.size(),0);
        total[0]=num[0];
        total[0]=num[0];
        if(num[1]>num[0])
            total[1]=num[1];
        else
            total[1]=num[0];
        int t=0;
        for(int i=2;i<num.size();i++)
        {
            t=num[i]+total[i-2];
            if(t>total[i-1])
                total[i]=t;
            else
                total[i]=total[i-1];
        }
        int max=0;
        for(i=total.size()-1;i>=0;i--)
        {
            if(total[i]>max)
                max = total[i];
        }
        return max;
    }

    然后看了些别人写的,羞愧啊。

    【转】一个显然的dp。 best0表示必须不选择下一个房间,best1表示可以选择下一个房间的最大收益。
    best1' = best0 因为不选第i个 在下一个房间就可以选了
    best0' = max(best0, best1 + num[i]) 尝试选择num[i],如果不更优,还不如不选它…… 

     int rob(vector<int> &num) {
            int best0 = 0, best1 = 0;
            for (int i = 0; i < num.size(); ++i) {
                int temp = best1 + num[i];
                best1 = best0;
                best0 = max(best0, temp);
            }
            return max(best0, best1);
  • 相关阅读:
    Struts2 参数传递总结
    简单的 MySQL 用户管理
    一道好题
    javascript 常用代码大全(2) 简单飞扬
    读取word和pdf文件的几种方法 简单飞扬
    模拟身份证号码JS源代码 简单飞扬
    兵法感悟 简单飞扬
    跨应用Session共享 简单飞扬
    放假前必须做的事情 简单飞扬
    javascript 常用代码大全(4) 简单飞扬
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4395831.html
Copyright © 2011-2022 走看看