LeetCode 198 House Robber

来源:互联网 发布:ornx奥尼克斯淘宝 编辑:程序博客网 时间:2024/05/29 03:15

题目:

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思想,对于从第4个房子开始,有两种选择,偷或不偷,假如不偷,则集成上一个房子的价值,假如偷,那么再从隔一个的还是隔两个的两个之间选择一个最大的加上这一个房子的价值,核心式是:

dp[i] = max(dp[i-1], max(dp[i-2], dp[i-3]) + nums[i]);

同时更新ans,因为每一个房子的dp值都是目前看来最大的,所以只需要判断隔一天和隔两天即可,三天及以上就不是最大值了。

代码如下:

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


呃。。看了下最优解,果然也是dp,不过比我这种思路更为简单(写的时候没改出来,以为不正确,,,还是太菜),对于每个房子而言,都有两种选择,偷或则不偷,不偷的话,结果同上一个房子,假如偷,那么结果就是nums[i] + dp[i-2],最终在两个选择种选择较大的。

代码如下:

class Solution {public:    int dp[11111];        int rob(vector<int>& nums) {        if (nums.empty()) return 0;        else if (nums.size() == 1) return nums[0];        else if (nums.size() == 2) return max(nums[0], nums[1]);        int ans = nums[0];        dp[0] = nums[0];        dp[1] = max(dp[0], nums[1]);                for (int i = 2; i < nums.size(); i ++) {            dp[i] = max(dp[i-1], dp[i-2] + nums[i]);            ans = max(ans, dp[i]);        }        return ans;    }};
第一次没改出来的原因在第 dp[1] 的赋值上,dp[1] 应该是在前两个种选择大者,这样才能保证在之后的运算中,保证加到的dp一定是最大的。


原创粉丝点击