java - 短算法(递归)的试运行问题

标签 java algorithm recursion

public class Algo{
    public static void main(String[] args){
        System.out.println(bar(4));
    }
    static int bar(int n){
        if(n==0 || n==1){
            return 1;
        }else{
            return n-bar(n-1);
        }
    }
}

所以我认为上面的代码是这样做的:

n=4: 4-(4-1) = 4-3 = 1
n=3: 1-(3-1) = 1-2 = -1
n=2: -1-(2-1) = -1-1 = -2
n=1: Now we get into the if-statement, this basically means that bar(1) = 1, so in the end we have that -2-1 = -3

但是当我编译并运行它时,我得到了不同的输出,我不明白为什么..?

Output: 2

我尝试了另一种与这个算法非常相似的算法(只是带有乘法符号,也就是 faculty)并且在这次试运行中它成功了。但它似乎不适用于该算法。

最佳答案

这是它的计算方式:

bar(4) = 
4 - bar(3) = 
4 - (3 - bar(2)) = 
4 - (3 - (2 - bar(1))) = 
4 - (3 - (2 - 1))) 
4 - 3 + 2 - 1 = 
2

关于java - 短算法(递归)的试运行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091993/

相关文章:

java - 意外覆盖 : The following declarations have the same JVM signature error on specific classes hierarchy

c - 在我的程序中使用 findfile

ruby - 以*干净*的方式在 Ruby 中实现非常深的递归的正确方法是什么?

Java-如何将黑白图像加载到二进制中?

java - 我们应该使用什么方法来代替 Hazelcast.getMap ("Map")?

java - 使用 json-simple 时解析 JSON 字符串并保留键数据顺序,无需手动构造 HashMap

algorithm - 为什么我们在排序算法中使用术语 "non-descending"而不是 "ascending"?

algorithm - 轴对齐边界框与边界椭圆

在视频中查找单词位置的算法?

python - 参数拆包浪费堆栈帧