House Robber题目链接

  House Robber II题目链接

  1. 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.

  Credits:
  Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

    该题相当于从一个数组中取出一个或多个不相邻的数,使其和最大。具体代码如下:

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int sz = nums.size();
 5         int * dp = new int[sz];
 6         for(int i = 0; i < sz; i++)
 7         {
 8             if(i == 0)
 9                 dp[0] = nums[0];
10             else if(i == 1)
11                 dp[1] = max(nums[1], nums[0]);
12             else
13                 dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]);
14         }
15         return dp[sz - 1];
16     }
17 };
View Code

相关文章: