LeetCode——House Robber

来源:互联网 发布:哪些淘宝服装质量好的 编辑:程序博客网 时间:2024/06/02 06:46

LeetCode——House Robber

# 198

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.

这一题的目的是求一个非负数组中最大的子序列,注意不能有两个相邻的元素。这一题明显是动态规划的题目,不是很难,把dp公式写出来就好了。就是用一个dp数字记录到第i个元素为止的最大子序列。

  • C++
class Solution {public:    int rob(vector<int> &num) {        if (num.size() <= 1) return num.empty() ? 0 : num[0];        vector<int> dp = {num[0], max(num[0], num[1])};        for (int i = 2; i < num.size(); ++i) {            dp.push_back(max(num[i] + dp[i - 2], dp[i - 1]));        }        return dp.back();    }};

这里需要注意的是,对于vector的元素,输入还是使用push_back比较好,用直接赋值的话会出现问题,我尝试解决了下,发现反倒麻烦,没必要。直接用vector的函数就好了。常用的函数就那么几个,多用也就记得了。

还有一种思想,就是对奇偶元素分别进行处理。其实跟上面的dp是一样的,只不过是分别处理。

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

可以写的简洁一点。

  • C++
class Solution {public:    int rob(vector<int> &nums) {        int a = 0, b = 0;        for (int i = 0; i < nums.size(); ++i) {            int m = a, n = b;            a = n + nums[i];            b = max(m, n);        }        return max(a, b);    }};
原创粉丝点击