动态规划系列 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 }