2012-02-08 110 views
2

我在java中遇到了這個基本的遞歸問題,任何指針都會很棒。基本Java遞歸方法

「編寫一個靜態遞歸方法來打印出 幾何序列的第n項:2,6,18,54。」

從我可以收集的代碼中的某處我應該遞歸地乘以3,但我正在努力弄清楚如何做到這一點。我知道我需要終止聲明,但是什麼時候發生?我需要輔助方法嗎?

回答

7

A Recursive Function是一個函數,其實現引用自身。下面是一些有趣的例子:

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」,它僅適用於小的數字是好的(由於整數溢出問題)。以下類是所有類型/數字更好:

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

這是遞歸的最簡單的例子。

您需要一個方法聲明。

您需要檢查是否已達到末端。

否則,您需要再次調用該方法,使得一個術語和另一個術語之間的差異變得很小。

1

是的,你需要一個終止條件 - 基本上當你採取儘可能多的步驟,你需要。因此,考慮如何從一個呼叫轉換到另一個呼叫:

  • 您將如何傳播結果到目前爲止?
  • 你需要額外的狀態來跟蹤你需要採取多少步驟?
  • 你打算從方法中返回什麼?
1

這裏是一個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); 
     } 
    } 

所以,當你運行函數輸入的參數

  • 「計數器」將永遠是0當你第一次叫它
  • 「迭代」是值的
  • 「值」是你的起始值,在你的情況下2
  • 「倍增器」是你多麼希望通過每一次迭代倍增,在您的案件3

運行時,它會檢查,看看是否計數器小於迭代每次。如果更多,則打印該值,計數器遞增,該值乘以乘數,並將相同的參數添加回該函數。

1

遞歸溶液: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 
}