下面的代码递归地将x减去1,直到它等于y。它打印一个表示递归过程的字符串。我不希望在字符串中打印x的起始值。
private static String createPath(int x, int y, String path) {
if (x > y) {
path += "(" + (x-1) + "," + y + ") ";
return createPath(x - 1, y, path);
}
else
return path += "(" + x + "," + y + ") ";
}当我输入如下内容时:
System.out.println(createPath(5, 1, ""));我得到以下输出:
(4,1) (3,1) (2,1) (1,1) (1,1) 为什么最后的值(1,1)被打印了两次?我注意到当我从(x-1)中删除(x-1)时
path += "(" + (x-1) + "," + y + ") ";输出变为:
(5,1) (4,1) (3,1) (2,1) (1,1)但同样,我不希望在字符串中打印(5,1)。此外,我也看过Why is my recursive loop printing the last value twice at the end?,但它似乎对我没有帮助。
发布于 2020-11-01 04:17:42
您的定义应如下所示:
private static String createPath(int x, int y, String path) {
if (x <= y) {
return path;
}
path += "(" + (x - 1) + "," + y + ") ";
return createPath(x - 1, y, path);
}这个定义将确保只要返回x <= y,就会返回path的值。
发布于 2020-11-01 04:16:08
很简单,因为当x==2和y==1条件x>y为true时,"(" + (x-1) + "," + y + ") "返回(1,1)
发布于 2020-11-01 04:20:26
正确的解决方案:
private static String createPath(int x, int y, String path) {
if (x > (y + 1))
return createPath(x - 1, y, path + "(" + (x - 1) + "," + y + ") ");
else
return path + "(" + (x - 1) + "," + y + ") ";
}注意,else分支中的if (x > (y + 1))和(x - 1)。
函数的执行顺序如下:
createPath(5, 1) => createPath(4, 1, "(4,1)");
createPath(4, 1) => createPath(3, 1, "(3,1)");
createPath(3, 1) => createPath(2, 1, "(2,1)");
createPath(2, 1) => createPath(1, 1, "(1,1)");
// and the last one in the else branch
createPath(1, 1) => createPath(1, 1, "(1,1)");正如您所看到的,您需要在else分支中添加(x - 1),并修改if语句,以便更早地到达else分支,以防止它低于1。
https://stackoverflow.com/questions/64625881
复制相似问题