Robbery, dynamic programming language C

You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .

Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, can steal the maximum amount to.

Example 1:

Input: [1,2,3,1] Output: 4 Explanation: Housing theft No. 1 (amount = 1), then the theft Housing 3 (amount = 3).
The maximum amount to theft = 3 + 1 = 4. Example 2:

Input: [2,7,9,3,1] Output: 12 Explanation: Housing theft No. 1 (amount = 2), 3 theft Housing (amount = 9), followed by theft. 5
No. Housing (amount = 1).
The maximum amount to theft = 2 + 9 + 1 = 12.

Source: stay button (LeetCode) link: https: //leetcode-cn.com/problems/house-robber
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

int max(int a, int b)
{
    return a>b?a:b;
}
int rob(int* nums, int numsSize){
//动态规划类型,考虑每一个最大值都可以有哪些子问题构成
//例如:我要从前四个里面偷取,怎么偷呢!
//细思极恐,好几种可能。怎么办呢?记住,编程时就是将乱麻给捋顺
//这些可能可以分为以下几大类:肯定含有第一家的,肯定含有第二家的但不含第一家,肯定含第
//三家的但不含第一第二家,肯定含有第四家但不含有第一第二第三家的,从这些可能中找到最大的
//所以设dp[i]表示从i到n家的最大价值
//dp[i]=max(num[i]+dp[i+2],num[i+1]+dp[i+3].......)
if(numsSize==0)
{
    return 0;
}
int* dp = (int*)calloc(numsSize,sizeof(int));
dp[numsSize-1]=nums[numsSize-1];
for(int i = numsSize-2;i>=0;i-- )
{
    for(int j = i;j<=numsSize-1;j++)
    {
        dp[i]=max(dp[i],nums[j]+(j+2<numsSize?dp[j+2]:0));
    }
}
return dp[0];
}

The results:
by
displaying details of
execution when used:
0 MS
, defeated in all C submission
100.00%
of user
memory consumption:
7.1 MB
, defeated in all C submission
26.94%
of users
show off:

发布了37 篇原创文章 · 获赞 1 · 访问量 632

Guess you like

Origin blog.csdn.net/zzuzhaohp/article/details/104467224