递推
时空复杂度皆为O(N)
import java.util.Scanner;
public class Main{
static int N = 50;
static int f[] = new int[N];
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
f[2] = 1;
//从第3项开始,每一项都等于前两项之和。
for(int i = 3; i <= n; i++)
f[i] = f[i - 1] + f[i - 2];
for(int i = 1; i <= n; i++)
System.out.print(f[i]+" ");
}
}
可以进一步优化使空间复杂度为O(1)
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
//注意数据范围0
int a = 0, b = 1;
if(n == 1) System.out.print(a);
else System.out.print(a+" "+b);
//从第3项开始,每一项都等于前两项之和。
for(int i = 3; i <= n; i++){
int c = a + b;
System.out.print(" "+c);
a = b;
b = c;
}
}
}