斐波那契数列
1,1,2,3,5,8,13…打印斐波那契数列数。
特点:前面两项之和,构成了后一项。
方法一:for循环
public static int f(int n) {
if (n==1||n==2) {
return 1;
}
int first=1;
int second=1;
int res=0;
for (int i = 3; i <=n; i++) {
res=first+second;
first=second;
second=res;
}
return res;
}
方法二:递归
public static int f(int n) {
if (n==1||n==2) {
return 1;
}
return f(n-1)+f(n-2);
}
每个递归定义必须至少有一个条件,满足时递归不再进行,即不再引用自身而是返回值退出。