198. House Robber

来源:互联网 发布:手机免root数据恢复apk 编辑:程序博客网 时间:2024/06/05 14:21

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.

思路参考:http://blog.csdn.net/chilseasai/article/details/50631233

解答:
动态规划一定要找递推公式。
对每一家房子,在其前一家房子偷不偷的前提下,有两种可能的情况。 前一家房子被偷了,它就不能再偷了。前一家房子没被偷,它可以被偷也可以选择不偷。
根据上述分析,得到递推公式:
money[i][0] = max(money[i - 1][0], money[i - 1][1])
上述公式表示,不偷第 i 家房子,当前最大收益就是前一家房子的最大收益,前一家房子可能被偷了,也可能没有被偷。
money[i][1] = money[i - 1][0] + nums[i]
上述公式表示,要偷第 i 家的房子,必须在不偷第 i-1 家房子的前提下,才能加上偷第 i 家获得的收益。

class Solution {  public:      int rob(vector<int> &num) {          if(num.size() == 0) return 0;        int money0 = 0;   // 表示没有选择当前house        int money1 = num[0];   // 表示选择了当前house          for(int i = 1; i < num.size(); i++){            int temp = money0;              money0 = max(money0, money1); // 没有选择当前house,那么它等于上次选择了或没选择的最大值              money1 = temp + num[i]; // 选择了当前houses,值只能等于上次没选择的+当前house的money          }          return max(money0, money1);     }  };  
原创粉丝点击