1.普通递归 2.记忆性递归 3.遍历 public static void main(String[] args) { long start1 = System.currentTimeMillis(); long result1 = recursion(50); long end1 = System.currentTimeMillis(); System.out.println("result1结果:"+result1+",耗时:"+(end1-start1)); // result1结果:20365011074,耗时:61878 Long[] array = new Long[51]; long start2 = System.currentTimeMillis(); long result2 = recursion2(array,50); long end2 = System.currentTimeMillis(); System.out.println("result2结果:"+result2+",耗时:"+(end2-start2)); // result2结果:20365011074,耗时:1 long start3 = System.currentTimeMillis(); long result3 = foreach(50); long end3 = System.currentTimeMillis(); System.out.println("result3结果:"+result3+",耗时:"+(end3-start3)); // result3结果:20365011074,耗时:0 } private static long recursion(int x){ if(x == 0){ return 1L;} if(x == 1){return 1L;} return recursion(x-1)+recursion(x-2); } private static long recursion2(Long[] array,Integer x){ if(x == 0){ array[0] = 1L; return 1L; } if(x == 1){ array[1] = 1L; return 1L; } if(array[x] == null) { array[x] = recursion2(array,x-1)+recursion2(array,x-2); }; return array[x]; } private static long foreach(Integer x) { long fa = 1; long fb = 1; long fab = 0; for (int i = 2;i <= x;i++) { fab = fa + fb; fa = fb; fb = fab; } return fab; }
斐波那契
最新推荐文章于 2024-01-05 10:30:21 发布