普通递归与改进后的递归

public class Recursion {
 public int fab(int n) {
  if (n <= 2) {
   return 1;
  }
  return fab(n - 1) + fab(n - 2);
 }

 int values[] = new int[45];

 public int fab2(int n) {
  if (values[n] != 0) {
   return values[n];
  }
  int t = n;
  if (n <= 2) {
   return 1;
  } else {
   t = fab2(n - 1) + fab2(n - 2);
   values[n] = t;
  }
  return t;
 }

 public static void main(String[] args) {
  Recursion rec = new Recursion();
  long st = System.currentTimeMillis();
  System.out.println(rec.fab(40));
  System.out.println("递归未改进前:"+(System.currentTimeMillis() - st));
  st = System.currentTimeMillis();
  System.out.println(rec.fab2(40));
  System.out.println("递归未改进后:"+(System.currentTimeMillis() - st));
 }
}

 

改进后的递归只是多占用了部分空间,但是节约了时间。我们可以找到一个平衡,使程序达到最优。

你可能感兴趣的:(递归)