[英]C# get fibonacci IEnumerable<int> with recursion.. I want it to return all the numbers, not only the last one
static IEnumerable<int> FibonacciByLength(int length)
{
if (length <= 1)
yield return 1;
else
yield return FibonacciByLength(length - 1).Last() +
FibonacciByLength(length - 2).Last();
}
該代碼僅返回最后一個值,但我希望它返回所有它們。
如果length
大於1
,則需要讓我們yield return
FibonacciByLength(length - 1)
每個數字:
static IEnumerable<int> FibonacciByLength(int length)
{
if (length == 1) yield return 1;
else if (length == 2)
{
yield return 1;
yield return 1;
}
else
{
foreach (var fib in FibonacciByLength(length - 1))
yield return fib;
yield return FibonacciByLength(length - 1).Last() + FibonacciByLength(length - 2).Last();
}
}
但我建議您不要使用遞歸來避免重復計算:
static IEnumerable<int> FibonacciByLength(int length)
{
int a = 1;
int b = 0;
for (int i = 1; i <= length; i++)
{
int c = a + b;
a = b;
b = c;
yield return c;
}
}
如果您不受傳遞給方法的參數的限制,建議您執行以下操作
static IEnumerable<int> FibonacciByLength(int maxValues, int valuesCalculatedSoFar = 0, int previousValue1 = 0, int previousValue2 = 0)
{
int nextValue;
if (valuesCalculatedSoFar < 2)
{
nextValue = 1;
}
else
{
nextValue = previousValue1 + previousValue2;
}
yield return nextValue;
valuesCalculatedSoFar++;
if (valuesCalculatedSoFar < maxValues)
{
foreach(var value in FibonacciByLength(maxValues, valuesCalculatedSoFar, previousValue2, nextValue))
{
yield return value;
}
}
}
您會使用哪個
var values = FibonacciByLength(10).ToList();
這樣做的原因是您避免不必要的呼叫。 使用此方法,如果要計算Fibonacci序列的前10個值,它將僅調用FibonacciByLength 10次。 在對FibonacciByLength的每次調用中,您都傳遞了計算下一個值所需的值,因此您不必重新計算它。
使用Arturo建議的方法,您將調用2089次。 這是因為有多個調用,例如FibonacciByLength(length-1).Last(),該調用需要重新計算整個序列直到傳入的長度才得到最后一個值。 如果只能傳遞長度值,則沒有其他選擇,必須忍受將要進行的指數級呼叫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.