LeetCode上的题目,能想出这个题目的人,真是。。。。。。。。。。。。。。。。。。。。。。。。让人头秃。。
本题说的是一个抢劫犯,去抢劫金店,但是他不能抢劫相邻金店,比如说 A B C D E ,五家金店,如果抢劫了A就不能抢劫B了,并且各家金店里黄金数量不一样,问这个抢劫犯要怎样抢劫金店才能获得最大利益。直接上代码,我还是分为递归和递推两种方法,并且只设置最大10家金店的初始值,所以测试值不要超过10
/*
LeetCode上题目
*劫匪抢劫金店,有n个金店,不能抢相邻金店,不然会触发报警器
每家金店金钱数不一样,怎样抢劫才能得到最大利益
*/
#include<stdio.h>
#include<stdlib.h>
int p[11]; /*假设有10家金店*/
int *r =NULL; /*保存重复计算的数据*/
/*
*比较大小函数
*/
int max(int a , int b){
return a > b ? a : b;
}
/*
*@count 输入的金店数
*/
int initGoldShop(int count){
p[1] = 1;
p[2] = 5;
p[3] = 8;
p[4] = 20;
p[5] = 10;
p[6] = 17;
p[7] = 17;
p[8] = 20;
p[9] = 24;
p[10] = 30;
r = (int *)malloc((count + 1) * sizeof(int)); /*内存分配*/
for(int i = 1 ; i <= count ;i++){
r[i] = -1;
}
return runGoldShop2(count);
}
/*
*递归:自顶向下
*抢劫金店运行函数
*@count 金店数目
*/
int runGoldShop1(int count){
if(count <= 0){
return 0;
}else if(count == 1){
return p[1];
}else if(-1 != r[count]){
return r[count];
}
int result = 0;
result = max(p[count] + runGoldShop1(count - 2) , runGoldShop1(count - 1));
r[count] = result;
return result;
}
/*
*递推:自底向上
*抢金店递推函数
*@count 金店数目
*/
int runGoldShop2(int count){
int r1 = p[1];
int r2 = max(p[1] , p[2]);
int r3 = 0;
for(int i = 3 ; i <= count ;i++){
r3 = max(p[i] + r1 , r2);
r1 = r2;
r2 = r3;
}
return r3;
}
感觉这种题意义不大,了解思想就好。。。。。。。。。。
希望各位批评指正(*_*)