在过去的几个小时里,我试图理解为什么这个程序的输出表现得如此奇怪。递归函数的第一部分对我来说很有意义,但是不幸的是,我发现其余部分非常困惑。
我想知道为什么程序会倒退,甚至添加到一个应该被减去的变量。这对我来说没有任何意义。如果有任何帮助,我将不胜感激。
这是我的递归函数:
public static void threeWays(int id, int n) {
if (n >= 0) {
System.out.println(id + "=" + n);
threeWays(id + 1, n - 1);
threeWays(id + 1, n - 2);
threeWays(id + 1, n - 3);
}
}
public static void main(String[] args) {
threeWays(1, 4);
}
这是输出:
1=4
2=3
3=2
4=1
5=0
4=0
3=1
4=0
3=0
2=2
3=1
4=0
3=0
2=1
3=0
最佳答案
Python3版本:
def threeWays(f, i, n):
if n >= 0:
print(f, i, '=', n)
threeWays('1st', i + 1, n - 1)
threeWays('2nd', i + 1, n - 2)
threeWays('3rd', i + 1, n - 3)
threeWays(' ', 1, 4)
乍一看,它可以,可以看起来像DFS但实际上不是...
当 threeWays
从 2nd 和 3rd threeWays
递归调用时,第 1 或 1st 和 2nd threeWay
也会被调用。 ..!
threeWays(' ', 1, 4) -> 1 = 4
threeWays('1st', 2, 3) -> 1st 2 = 3
threeWays('1st', 3, 2) -> 1st 3 = 2
threeWays('1st', 4, 1) -> 1st 4 = 1
threeWays('1st', 5, 0) -> 1st 5 = 0
threeWays('1st', 6, -1)
threeWays('2nd', 5, -2)
threeWays('3rd', 5, -3)
threeWays('2nd', 4, 0) -> 2nd 4 = 0
threeWays('3rd', 4, -1)
threeWays('2nd', 3, 1) -> 2nd 3 = 1
threeWays('1st', 4, 0) -> 1st 4 = 0
threeWays('2nd', 4, -1)
threeWays('3rd', 4, -2)
threeWays('3rd', 3, 0) -> 3rd 3 = 0
...
关于java - 坚持理解递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584998/