Java深入学习19:算法-1步2步走台阶
如下
public class RrecursionTest { //题目:台阶共n层,每次只能走1步或2步,一共多少走法。 //方案1-递归 private static long f(long n){ if(n == 1 || n == 2){ return n; } return f(n-1) + f(n-2); } //方案2-循环 private static long loop(long n){ if(n == 1 || n == 2){ return n; } long one = 2; long two = 1; long sum = 0; for(long i =3; i<n+1; i++){ sum = one + two; two = one; one = sum; } return sum; } public static void main(String[] args) { long n = 50; long time1 = System.currentTimeMillis(); System.out.println(f(n)); long time2 = System.currentTimeMillis(); System.out.println("f time: " + (time2 - time1)); System.out.println(loop(n)); long time3 = System.currentTimeMillis(); System.out.println("loop time: " + (time3 - time2)); } }