虽然有点幼稚,但我必须问一下:
在这里提到的Bytelandian Gold coin问题 - http://www.codechef.com/problems/COINS/, 被称为典型的DP问题,即使我已经了解了DP和递归的基础知识,但我仍然很难理解它的解决方案。
# include <stdio.h>
# include <stdlib.h>
long unsigned int costArray[30][19];
unsigned int amount;
unsigned int currentValue(short int factor2,short int factor3)
{
int j;
unsigned int current = amount >> factor2;
for(j=0;j<factor3;j++)
current /= 3;
return current;
}
long unsigned int findOptimalAmount(short int factor2,short int factor3)
{
unsigned int n = currentValue(factor2,factor3);
if(n < 12)
{
costArray[factor2][factor3] = n;
return (long unsigned int)n;
}
else
{
if(costArray[factor2][factor3] == 0)
costArray[factor2][factor3] = (findOptimalAmount(factor2+1,factor3) + findOptimalAmount(factor2,factor3+1) + findOptimalAmount(factor2+2,factor3));
return costArray[factor2][factor3];
}
}
int main()
{
int i,j;
while(scanf("%d",&amount) != EOF)
{
for(i=0;i<30;i++)
for(j=0;j<19;j++)
costArray[i][j] = 0;
printf("%lu\n",findOptimalAmount(0,0));
}
return 0;
}
比如它的递归是如何工作的?costArray的大小是如何决定为30x19的?
此外,我如何提高解决这类问题的思维能力?
谢谢!
findOptimalAmount
函数。递归将变得非常明显。 - Felix Frank