斐波那契数(动态规划和递归)
递归写法:
public class Test { public static void main(String[] args) { feibo test = new feibo(); for (int n = 1; n <= 15; n++) { System.out.println(test.feibo(n)); } } } class feibo { public int feibo(int n) { if (n == 2||n==1) { return 1; } else { return feibo(n - 2) + feibo(n - 1); } } }
动态规划写法(降低时间复杂度):
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /* * 递归时间复杂度为2^n */ //动态规划求Fibo class Test2{ public static void main(String[] args) { Scanner scanner =new Scanner(System.in); Main main = new Main(); while (scanner.hasNext()){ System.out.println( main.fibo(scanner.nextInt())); } } } class Main{ public int fibo(int n){ List<Integer> list =new ArrayList(); list.add(1); list.add(1); for (int i = 2;i < n; i++ ){ list.add(list.get(i-2)+list.get(i-1)); } return list.get(n-1); } }