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.
实际上就是给一个序列,取不连续的一些数字,使得其和最大,求和。
然后就想到了DP,试了下,果然可行。

class Solution {
public:
    int rob(vector& nums) {
        int n = nums.size();
        vector dp(n+2, 0);
        for (int i=2; i

然后看了看大神们的答案,实际上用O(1)空间就可以了,代码如下:

class Solution {
public:
    int rob(vector& nums) {
        int n = nums.size();
        int a = 0, b = 0;
        for (int i=0; i

实际上就是存储dp[i-1]dp[i-2]就可以了。

你可能感兴趣的:(House Robber)