我有一个有趣的问题要解决我给出start
和end
整数值的位置,我需要从start
打印到end
然后从{{ 1}}使用递归来end
。
例如 -
start = 2和end = 5然后该方法应打印以下内容,
start
我可以使用代码
轻松完成第一部分2,3,4,5,4,3,2
但是,然后在递归中增加起始值,我无法找到减少的位置。如何改进我的代码只提一种方法可以使用?目前,它只是打印
public static void countUp(int start, int end) {
System.out.println(start);
if(start< end){
countUp(start+1, end);
}
}
答案 0 :(得分:6)
试试这个,
public static void countUp(int start, int end) {
System.out.println(start);
if(start< end){
countUp(start+1, end);
System.out.println(start); //backtracking
}
}
答案 1 :(得分:4)
countUp(start+1, end);
不会增加start
- 它会计算start+1
并将结果传递给countUp
的新调用,该调用将具有自己的1} em> start
的值。在当前调用中,start
仍然具有相同的值。递归调用完成后,控制将返回当前调用,并在调用后继续。如果您只是在方法结束时打印start
会怎样?
答案 2 :(得分:0)
只有递归的问题的解决方案如下,
public static void countUp(int start, int end) {
System.out.println(start);
if( start< end){
countUp(start+1, end);
}
if( start != end){
System.out.println(start);
}
}