leetcode198. House Robber
198. 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.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
一直都不清楚动态规划,看了一些视频还是懵懵懂懂的感觉,在leetcode上做了一道DP的题,记录一下
在做这题时,也看了别人的代码,自己太弱,一直看不懂为啥那样写,懂别人思路,不懂别人为啥那样写代码。。。。
自己写了一个代码,运行成功。
思路:用一个数组dp记录从开始到现在偷到的钱的总数。dp[i]代表前i家中能偷到的最大钱数。dp[n]即为所有的前N家能偷到的最大钱数,也即为所求结果。
先记录nums中前两个的钱数。然后用一个循环从第三个开始,求能偷到的最大钱数。偷到第三家时的最大钱数,有两种可能,第一家的钱+第三家的钱或者是第二家的钱,这两个中去一个最大值,就是前三家中能偷到的最大钱数
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (!n) return 0; int dp[n];//dp就代表到达n时的最大价值 dp[0] = nums[0]; if (n < 2) { return dp[n - 1]; } dp[1] = max(nums[0], nums[1]); for (int i = 2; i < n; i++) { dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); } return dp[n - 1]; } };