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.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

翻译

你是一个专业的盗贼计划沿着一条街偷东西. 每间屋子都有确定数额的存款, 唯一能阻止你偷他们的是,相邻两件屋子有安全系统连接,如果相邻两间屋子在同一天晚上被传入它就会自动练习警察。

给你一个非负列表来表示每间屋子有的钱数, 确定今晚你能在不惊动警察的情况下所能偷到的最多的钱数。.

例 1:

输入: [1,2,3,1]
输出: 4
说明: 偷房子 1 (钱= 1) 接着偷房子 3 (钱 = 3).
             你能偷到的总钱数是 = 1 + 3 = 4.

例 2:

输入: [2,7,9,3,1]
输出: 12
解释: 偷房子 1 (钱= 2), 偷房子 3 (钱= 9) 接着偷房子 5 (钱= 1).
             你能偷到的总钱数是 = 2 + 9 + 1 = 12.

程序

int max(a,b)
{return a>b?a:b;}
    
int rob(int* nums, int numsSize){
    if(numsSize==0)return 0;
    if(numsSize==1)return nums[0];
    int f0 = nums[0];
    int f1 = max(nums[0],nums[1]);
    int temp = 0;
    for(int i=2;i

198. House Robber_第1张图片

总结

  1. 了解了状态转移方程这个概念(不太确定)。
    (1) 将最终要求的情况表示为状态n。(这个题最后调查了多少家就是n,在这调查的n家中,所能偷到的最高钱数就是f(n) 至于为什么调查就是因为不能偷相邻的两间屋子);
    (2) 怎样才能知道n家最多能偷到多少钱,这就要写出一个式子(状态转移方程),
    (3) 本题中要知道n家最多能偷多少钱,就要知道(f(n-1))和(f(n-2)+第n家能偷到的钱)哪一个大,哪一个就是f(n)
    (4) f(1))和(f(2)+第3家能偷到的钱)哪一个大,哪一个就是f(3)

    f(1)为第一家的钱数
    f(2)为前两家钱数较大的一家
    要点:要想知道前n家,只需要知道所需的前两个状态,而不用管他们是怎样得出的

你可能感兴趣的:(Leetcode,leetcode,c,编程,dynamic,programing)