[英]How to convert a recursive function (with two base cases) to iterative function?
假設存在以下遞歸函數:
int foo (int num)
{
if (num == 1)
return an int
else if (num == 2)
return another int
else
num foo(num-2) + foo(num-1)
}
我的問題是:
1)如何將其他部分轉換為各自的迭代版本? 我遇到了許多函數,其中一般情況是將常量乘以其遞歸調用(或相加)。 盡管我之前從未遇到過這種情況。
else
return 3 * foo(n-1)
2)您能否給我一些有關如何將遞歸函數轉換為迭代函數的技巧,尤其是調用兩次自己的函數並計算其總和或乘積的技巧(如上面的示例)?
非常感謝。
(編輯)
假設在調用此函數之前已經進行了錯誤檢查。 Num始終大於0或(0,∞)
1)
int foo (int num)
{
int foo1 = an int;
int foo2 = another int;
if (num < 2)
return foo1;
for (int n=2; n<num; ++n)
{
int foo3 = foo1+foo2;
foo1 = foo2;
foo2 = foo3;
}
return foo2;
}
2)迭代實現通常需要對問題和解決方案有更深入的了解。 在這種情況下,我發現計算foo(n)需要計算所有foo(1)... foo(n),並且如果您記得前面的兩個,則可以一步完成每一步。
創建一個填充表A
的函數,其中表A[i]
包含foo(i)
的值。 也就是說,將return
替換為A[i] =
,並將對foo(i-1)
遞歸調用替換為查找A[i-1]
。 示例代碼:
int foo (int num)
{
std::vector<int> results(num+1);
for (int i = 1; i <= num; ++i) {
if (i == 1)
results[i] = an int
else if (i == 2)
results[i] = another int
else
results[i] = results[i-2] + results[i-1]
}
return results[num];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.