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
我尝试了另一种非常类似于此算法的算法(只有乘法符号也称为教师)并且通过这种干运行它已经奏效了。但它似乎不适合这种算法。
答案 0 :(得分:2)
鉴于代码会递归到n-1
,如果您按照增加n
的顺序考虑结果会更容易,因为您可以简单地替换上一行的结果。< / p>
n working result
====================
0 (by def) 1
1 (by def) 1
2 2-1 1
3 3-1 2
4 4-2 2
答案 1 :(得分:2)
以下是它的计算方法:
bar(4) =
4 - bar(3) =
4 - (3 - bar(2)) =
4 - (3 - (2 - bar(1))) =
4 - (3 - (2 - 1)))
4 - 3 + 2 - 1 =
2
答案 2 :(得分:1)
bar(4) = 4 - bar(3) = 4 - 2 = 2
bar(3) = 3 - bar(2) = 3 - 1 = 2
bar(2) = 2 - bar(1) = 2 - 1 = 1
bar(1) = 1