[LeetCode]198. House Robber

来源:互联网 发布:西北师大知行学院贴吧 编辑:程序博客网 时间:2024/04/30 08:50

问题:

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.

答案:

class Solution {public:    //动态规划问题,result[i]中保存截止到i店所能得到的最多的钱    int rob(vector<int>& nums) {        int len = nums.size();        if(len == 0)            return 0;        if(len == 1)            return nums[0];        vector<int> result(len);        result[0] = nums[0];        result[1] = (nums[1]>nums[0] ? nums[1]:nums[0]);        for(int i = 2; i< len; ++i){            result[i] = max(result[i-1],result[i-2]+nums[i]);//截止到i家,要么这家不抢,result[i]为result[i-1],要么抢这家,那i-1就不能抢,那么result[i]=result[i-2]+这家的钱        }        return result[len-1];    }};
0 0