如何使用在 Java 中返回类型为 void 的递归方法



所以我了解如何使用具有除 void 以外的其他返回类型的递归方法。通常,我会在同一方法(在递归情况下)再次调用相同的方法,同时在调用中递减或递增一些值以达到基本情况。然后在某个时候达到基本情况并解决问题,因此它开始从每次调用返回值。沿着这些思路。


如果该方法具有返回类型 void,因此您无法调用该方法,因为它不会/无法返回任何内容,该怎么办?我正在尝试倒写一个句子,我已经使用 for 循环和可以返回字符串值的 resucrive 方法解决了这个问题,但我不确定如果它是空的,我不确定如何处理它,这是赋值所要求的。
编辑:我还应该提到句子只能在参数中传递

谢谢大家提供的信息和帮助!

递归不仅适用于返回值的方法/函数。递归仅意味着方法/函数调用自身。

您必须保证至少有一个停止条件,但这不需要函数返回值。这通常是通过增量更改函数每次递归调用自身时传递的一个或多个参数来实现的。当该/这些参数满足某个条件时,您的函数不再调用自身,并且所有挂起的操作都将被解决。

我不完全了解您要执行的任务,但这里有一个向后写入字符串的递归函数示例。我使用伪函数的名称希望是不言自明的。

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);
    }
}

您可以使用任何可变对象作为递归函数的参数来存储结果。例如,你提到的反判问题可以写成:

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);

就像在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);
  }
}

祝你好运。

最新更新