House Robber

Description:

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.

Code:

 1  int rob(vector<int>& nums) {

 2         if (nums.empty())

 3             return 0;

 4         size_t length = nums.size();

 5         int result = 0;

 6         if (1==length)

 7             return nums[0];

 8         else if (2==length)

 9             return (nums[0]>=nums[1])?nums[0]:nums[1];

10         else

11         {

12             int p = nums[0], q=(nums[0]>=nums[1])?nums[0]:nums[1];

13             for (int i = 2; i <= length-1; ++i)

14             {

15                 int temp = p+nums[i];

16                 result=(temp>=q)?temp:q;

17                 p = q;

18                 q = result;

19             }

20         }

21         return result;

22     }

令f(n)表示从1号房子到n号房子可以偷到的最大钱数,则:

f(n)=max(f(n-1), f(n-2)+an)

你可能感兴趣的:(r)