当前位置: 代码迷 >> J2EE >> 看看这个程序的输出结果是什么,能不能改进算f(n)的方法。解决办法
  详细解决方案

看看这个程序的输出结果是什么,能不能改进算f(n)的方法。解决办法

热度:588   发布时间:2016-04-22 02:50:49.0
看看这个程序的输出结果是什么,能不能改进算f(n)的方法。

public class Squence {
public static void main(String[] args) {
System.out.println(fun(1,1,3));
}
public static int fun(int A,int B,int n){
if(n==1 || n==2){
return n;
}
else{
return A*fun(A,B,(n-1))+B*fun(A,B,(n-2));
}
}

}


------解决方案--------------------
你还想怎么改进?
------解决方案--------------------
递归就是这样,内存消耗大
------解决方案--------------------
为什么这么写,只有你自己知道
要想递归了多少次,可以统计一下
Java code
public class Squence {        static int count =0;    public static void main(String[] args) {        System.out.println(fun(1, 1, 3));                System.out.println("一共循环次数:"+count);    }    public static int fun(int A, int B, int n) {                count++;        if (n == 1 || n == 2) {            return n;        } else {            return A * fun(A, B, (n - 1)) + B * fun(A, B, (n - 2));        }    }}
  相关解决方案