4.3小节:递归(对应编号583)
A题 吃糖果
#include <stdio.h>
#include <stdlib.h>
int count(int n)
{
if(n==1) return 1;
else if(n==2) return 2;
else return count(n-1)+count(n-2);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
printf("%d\n",count(n));
}
return 0;
}
总结:本题while控制输入,n>0,边界为n == 1和n == 2,选择为1和2所以count(n)受count(n-1)和count(n-2)影响。本题或许也可以用动态规划思想解决,用数组依次记录也可。