Java中的递归和堆栈
我正在研究堆栈和递归。假设我有这样一种方法:Java中的递归和堆栈,java,recursion,Java,Recursion,我正在研究堆栈和递归。假设我有这样一种方法: public class RecursionStack { public String countIterative(int from, int to) { // do something? Use a loop? } } 有人能帮我吗?比如,我如何使用循环从给定的数字返回字符串到给定的数字?所以当我打印出来时,它看起来像 System.out.print(RecursionStack.count( 5, 11 ))
public class RecursionStack {
public String countIterative(int from, int to) {
// do something? Use a loop?
}
}
有人能帮我吗?比如,我如何使用循环从给定的数字返回字符串到给定的数字?所以当我打印出来时,它看起来像
System.out.print(RecursionStack.count( 5, 11 ));
prints: 5 6 7 8 9 10 11
多谢各位 试试这个:
public class RecursionStack {
public static String countIterative(int from, int to) {
// the following if is your base case
// and it is from here that you can stop
// performing recursion
if (from == to) { return " " + to;}
else { // this else is default and is the basis of the "recursiveness" of the function
String toReturn = from + " " + countIterative(from+1, to);
return toReturn;
}
}
}
试试这个:
public class RecursionStack {
public static String countIterative(int from, int to) {
// the following if is your base case
// and it is from here that you can stop
// performing recursion
if (from == to) { return " " + to;}
else { // this else is default and is the basis of the "recursiveness" of the function
String toReturn = from + " " + countIterative(from+1, to);
return toReturn;
}
}
}
递归方法是调用自身的方法。此外,如果没有类的实例,则不能调用非静态方法。你可以写一个迭代版本,比如
public static void countIterative(int from, int to) {
for (; from <= to; from++) {
System.out.printf("%d ", from);
}
}
您将获得请求的输出。递归方法是一种调用自身的方法。此外,如果没有类的实例,则不能调用非静态方法。你可以写一个迭代版本,比如
public static void countIterative(int from, int to) {
for (; from <= to; from++) {
System.out.printf("%d ", from);
}
}
您将获得请求的输出。您自己尝试过什么吗?递归方法是调用自身的方法。所有递归函数都必须具有终止此循环行为的基本条件和调用方法本身的递归定义。搜索一些递归问题的例子,然后试着为自己定义一个。如果在尝试之后你遇到了一些问题,那么带着你的问题回到这里并征求建议!有什么问题吗?这就像从到循环,然后打印每个索引值。应该很简单。谢谢你的建议。你自己试过什么吗?递归方法是调用自身的方法。所有递归函数都必须具有终止此循环行为的基本条件和调用方法本身的递归定义。搜索一些递归问题的例子,然后试着为自己定义一个。如果在尝试之后你遇到了一些问题,那么带着你的问题回到这里并征求建议!有什么问题吗?这就像从到循环,然后打印每个索引值。应该很简单。谢谢你的建议