15算法课程 198. House Robber

来源:互联网 发布:js 判断手机号码 编辑:程序博客网 时间:2024/06/12 22:32


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.


solution:

由于抢劫的房间不能相邻,所有我们可以看到加入nums[i]与不加入nums[i]的区别。
我们找到递归公式dp[i] = max(dp[i-1],dp[i-2] + nums[i]);


code:

class Solution {public:    int rob(vector<int>& nums) {        vector<int> dp(nums.size(),0);        if(nums.size() <= 0){            return 0;        }        dp[0] = nums[0];        for(int i = 1;i < nums.size();++i){            if( i >= 2){               dp[i] = max(dp[i-1],dp[i-2]+nums[i]);             }else{               dp[i] = max(dp[i-1],nums[i]);            }        }        return dp[nums.size()-1];    }};


原创粉丝点击