在过去的两个小时里,我试图理解为什么该程序的输出表现出如此怪异的方式。递归函数的第一部分对我来说很有意义,但是,不幸的是,其余部分我感到非常困惑。
我想知道程序为什么向后退,甚至增加了应该减去的变量。这对我来说没有任何意义。谢谢您的帮助。
这是我的递归函数:
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
答案 0 :(得分:1)
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
递归调用threeWays
时,第一个或第一个和第二个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
...
答案 1 :(得分:0)
如果缩进输出以显示调用堆栈在每个点的深度,您可能会发现它更有用。我用System.out.println(" ".repeat(id) + n);
替换了您的打印声明,并收到了输出:
4
3
2
1
0
0
1
0
0
2
1
0
0
1
0
这里的结构是,每打印一个数字,下一个级别就会以降序显示下面的三个数字,直到达到零为止。这正是您的功能所要做的。