基本的Java递归方法

我在java中遇到这个基本的递归问题很麻烦; 任何指针都会很棒。

“编写一个静态递归方法来打印出几何序列的第n项:2,6,18,54。”

从我可以收集到的,代码中的某个地方,我应该递归地将某些东西乘以3,但我正在努力弄清楚如何做到这一点。 我知道我需要终止声明,但什么时候发生? 我需要辅助方法吗?

递归函数是一个实现引用自身的函数。 以下是一些有趣的例子:

public class Inception { public void dream() { boolean enoughDreaming = false; //Some code logic below to check if it's high time to stop dreaming recursively ... ... if(!enoughDreaming) { dream(); //Dream inside a Dream } } } 

并为您的问题的解决方案:

 public class GeometricSequence { public static void main(String[] args) { //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP. System.out.println(findNthNumber(5, 1, 2)); } public static int findNthNumber(int n, int count, int res) { return ((count == n)) ? res : findNthNumber(n, count+1, res *3); } } 

编辑

上面的类使用“int”,这仅适用于小数(因为Integer Overflow问题)。 以下类适用于所有类型/数字:

 public class GeometricSequence { public static void main(String[] args) { //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP. System.out.println(findNthNumber(2000, 1, new BigInteger("2"))); } public static BigInteger findNthNumber(int n, int count, BigInteger res) { return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3"))); } } 

这是递归的最简单示例。

你需要一个方法声明。

您需要检查是否已到达终点。

否则,您需要使用一个操作来再次调用该方法,该操作会使一个术语与下一个术语之间产生差异。

是的,你需要终止条件 – 基本上当你已经采取了所需的步骤时。 因此,请考虑您希望如何从一个呼叫转换到另一个呼叫:

  • 到目前为止,您将如何传播结果?
  • 您需要多少状态来跟踪您需要采取多少步骤?
  • 你打算从这个方法返回什么?

这是一个C#示例(我知道你在做Java,但它非常相似)

  public static void Recursive(int counter, int iterations, int value, int multiplier) { if (counter < iterations) { Console.WriteLine(value); counter++; Recursive(counter, iterations, (value * multiplier), multiplier); } } 

因此,当您运行该function时,请输入参数

  • 第一次调用时,“counter”将始终为0
  • “iterations”是n的值
  • 在你的情况下,“价值”是你的起始值2
  • “乘数”是指您希望在每次迭代中乘以多少,在您的情况下为3

每次运行时,它都会检查计数器是否小于迭代次数。 如果更多,则打印该值,计数器递增,该值乘以乘数,然后将相同的参数重新添加到函数中。

递归解决方案:Seq(1)是序列的第一个元素…. Seq(第n个)

 public static void main(String args[]) throws Exception { int x = Seq(3); //x-> 18 } public static int Seq(int n){ return SeqRec(n); } private static int SeqRec(int n){ if(n == 1) return 2; else return SeqRec(n - 1) * 3; } 

非递归解决方案:

 public static int Non_RecSeq(int n){ int res = 2; for(int i = 1; i < n; i ++) res *= 3; return res; } public static void main(String args[]) throws Exception { int x = Non_RecSeq(3); //x-> 18 }