动态规划系列 Leetcode 198. House Robber

Posted Hwangzhiyoung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划系列 Leetcode 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.

 1 #include <stdio.h>
 2 
 3 #include <vector>
 4 class Solution {
 5 public:
 6     int rob(std::vector<int>& nums) {
 7         if (nums.size() == 0){
 8             return 0;
 9         }
10         if (nums.size() == 1){
11             return nums[0];
12         }
13         std::vector<int> dp(nums.size(), 0);
14         dp[0] = nums[0];
15         dp[1] = std::max(nums[0], nums[1]);
16         for (int i = 2; i < nums.size(); i++){
17             dp[i] = std::max(dp[i-1], dp[i-2] + nums[i]);
18         }
19         return dp[nums.size() - 1];
20     }
21 };
22 
23 int main(){
24     Solution solve;
25     std::vector<int> nums;
26     nums.push_back(5);
27     nums.push_back(2);
28     nums.push_back(6);
29     nums.push_back(3);
30     nums.push_back(1);
31     nums.push_back(7);    
32     printf("%d\\n", solve.rob(nums));
33     return 0;
34 }

 

以上是关于动态规划系列 Leetcode 198. House Robber的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 198 House Robber 动态规划

算法刷题打卡041 | 动态规划9-打家劫舍系列

Leetcode198. 打家劫舍(经典动态规划+优化)

leetcode 198 动态规划

Leetcode之动态规划(DP)专题-198. 打家劫舍(House Robber)

#动态规划 LeetCode 198 打家劫舍