日期:2014-05-20  浏览次数:20596 次

看看这个程序的输出结果是什么,能不能改进算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));
        }
    }

}