1.最近在面试的时候遇到一题简单的递归题: a0=1 ,a1=1,a2=2,a3=3; an=a(n-1) + a(n-2)的代码。
代码如下:
#include<stdio.h>
int main (void)
{
int temp_1 = 1;
int temp_2 = 1;
int i, temp;
int n =30 ;
if (n == 0 || n == 1) {
temp_2 = 1;
} else {
for (i=2;i<=n;i++) {
temp = temp_1;
temp_1 = temp_2;
temp_2 = temp + temp_2;
}
printf("第a%d = %d\n", n, temp_2);
}
return 0;
}
以上的代码应该还有可修改之处,可以更加优化,但是这个可以不用递归的方式完成而达到目的。但是我们可以看到刚刚的代码定义了
许多的变量,这样可能会影响能存空间的分配,下面是用C++完成:
public class Test {
public static void main(String[] args) {
System.out.println(recursive(30));
}
public static int recursive(int i) {
// int a0=1;
// int a1=1;
// int a2=a1+a0;
// int a3=a2+a1;
if (i==0 || i==1) return 1;
return recursive(--i) + recursive(--i);
}
}