2016-02-28 643 views
0

所以我知道如何使用具有非void一些其他的返回类型的递归方法。通常我会在同一个方法中再次调用相同的方法(在递归情况下),同时在调用中减少或增加一些值以达到基本情况。然后在某个时刻到达基本案例并解决问题,因此它开始返回每次调用的值。沿着这些线。如何使用在java中具有返回类型void的递归方法?


如果什么方法返回void类型,所以你不能叫,因为它不会/不能返回什么方法?我试图向后写一句,我已经有一个for循环,并且可以返回一个字符串值resucrive方法解决了这两个,但我不知道如何,如果它是无效接近它这是任务是什么要求。
编辑:我还要提一句,只能通过参数

谢谢大家的信息和帮助!

+0

使用类级对象来保存递归数据。不好的做法,因为它很难跟踪递归问题/因为你的对象总是在变化,所以实际上很难实现递归。主要用于简单情况下,只和总和/连接一样。 –

回答

1

递归不与方法/返回值的功能才能正常工作。递归只意味着方法/函数自己调用。

你必须保证至少有一个停止条件,但并不要求函数返回一个值。这通常是通过递增地改变每次函数递归调用时通过的一个或多个参数来实现的。当那些/那些参数满足某个条件时,你的函数不再调用它自己,并且所有待处理的操作都被解决了。

我不完全了解你正在尝试做的,但这里的任务是向后将一个字符串递归函数的一个例子。我使用希望不言自明的名称使用PSEUDO函数。

public void writeBackwards(String str) { 
    // This is the negation of the stop condition, so the stop condition 
    // is when the string is empty, in which case this function will do 
    // nothing: 
    if (!str.isEmpty()) { 
     char firstCharacter = str.getFirstCharacter(); 
     str = str.removeFirstCharacter(); 
     writeBackwards(str); // the recursive call 
     // The following operation will be pending, waiting for the 
     // recursive call to be resolved first: 
     writeCharacter(firstCharacter); 
    } 
} 
+0

谢谢。我想我非常关注它需要实际返回的东西。我最终使用变量作为角色的空间持有者。它会将该字符从最后一个位置一直打印到开头,直到达到字符位置0的基本情况。所以变量将是最后一个字符,打印该变量,然后再次调用该函数减1个位置。我看了以前的例子,看起来很复杂,但这非常简单。 – pudge

0

可以使用可变对象为递归函数存储结果的参数。例如,你所提到的向后句子问题可以写成:

public void stringReverse(String s, int index, StringBuilder sb) { 
    if (index < 0) 
     return; 
    sb.append(s.charAt(index)); 
    stringReverse(s, index - 1, sb); 
} 

而且这样调用

StringBuilder sb = new StringBuilder(); 
stringReverse(mySentence, mySentence.length() - 1, sb); 
0

就像在C++中,你可以在指针传递,这里在Java中,你可以简单地传递在函数的类对象中保存从函数的递归调用生成的值。反映你的问题来计算斐波纳契数的一个简单例子如下。

public class ComputeFibonacci { 
    static class Fibonacci { 
    public int ith; 
    public int value; 
    Fibonacci(int a, int b) { 
     ith = a; 
     value = b; 
    } 
    } 

    private static void fibonacci(Fibonacci result) { 
    if (result.ith == 1 || result.ith == 2) { 
     result.value = 1; 
    } else { 
     Fibonacci left = new Fibonacci(result.ith - 1, 0); 
     Fibonacci right = new Fibonacci(result.ith - 2, 0); 
     fibonacci(left); 
     fibonacci(right); 
     result.value = left.value + right.value; 
    } 
    } 

    public static void main(String[] args) { 
    // Here we compute the 10th fibonacci number 
    Fibonacci f = new Fibonacci(10, 0); 
    fibonacci(f); 
    System.out.println("The result is " + f.value); 
    } 
} 

祝你好运。