1, 1, 2, 3, 5, 8, 13, 21, 34......获取第N位的值,算法的递归解决

//静态的计算次数;
private static int start = 0;
//main方法
public static void main(String[] args) {
System.out.println(test(9));
}
//测试方法
public static int test(int end) {
  start = 0;
  //小于3位无意义,直接返回1
if (end < 3) {
return 1;
}
  //初始化数组
int[] a = new int[end];
a[0]=1;
  start+=1;

a[1]=1;
  start+=1;

  //当计算位数大于2,调用递归方法
return test(a, end);
}
//递归方法
public static int test(int[] a, int end) {
   //递归的终止条件
if (start == end) {
     //返回所需计算的值
return a[end - 1];
}

  //规律:第N位的值=(N-1)位+(N-2)位
a[start ] = a[start-1] + a[start - 2];

  //记录计算次数
start+=1;

  //开始递归
return test(a, end);
}
posted @ 2021-10-26 09:54  滔滔江水连绵不绝  阅读(464)  评论(0)    收藏  举报