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<int>& nums) {
        int n = nums.size();
        vector<int> dp(n+2, 0);
        for (int i=2; i<n+2; i++) {
            dp[i] = max(dp[i-1], dp[i-2] + nums[i-2]);
        }
        return dp[n+1];
    }
};

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

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容