码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划系列 Leetcode 198. House Robber

时间:2018-04-07 17:49:30      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:return   color   ber   tin   pre   use   cer   present   \n   

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

标签:return   color   ber   tin   pre   use   cer   present   \n   

原文地址:https://www.cnblogs.com/Hwangzhiyoung/p/8733676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!