leetcode刷题,总结,记录,备忘 198

leetcode198House 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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

中秋两天偷了个懒,其实我应该上星期就写这篇的。

这个题目一开始我自己有想法,是用一大堆if判断写的,感觉很乱,很杂,遂放弃,自己没想出别的方式,又去翻人家的博客了。

发现很多题目都有类似的解法,使用一个递推的公式,用另一个数组做辅助,每次求出数组一个位置上的最大值,然后使用公式继续求导,感觉很方便,简易。自己稍微走遍流程的话可以很轻松的看懂,但是不知道是如何想出这样的方法的。有空去研究下算法方面的书籍。不对代码做解释了,代点数字走个流程就能看懂。

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


你可能感兴趣的:(leetcode刷题,总结,记录,备忘 198)