[英]What is the time complexity of a recursive function that calls itself N times with one less?
[英]C++ Recursive Function that calls itself N Times?
假設我有一個功能:
int recursive(int NbProducts, int NbPlates, int NbPositions)
{ //the following is a recursive function that will call itself 3 times
//code to be repeated goes here
recursive(int NbProducts, int NbPlates, int NbPositions);
}
我不知道的是如何使該函數知道它的遞歸編號以及如何停止它。 有什么有效而聰明的方法嗎? 如果有幫助,我正在使用Boost算法。
在執行函數之前將其傳遞給參數並進行檢查。如果迭代結束,則返回結果,否則繼續
int recursive(int NbProducts, int NbPlates, int NbPositions,int repeat)
{
repeat --;
if(repeat==0)
return result;
else
recursive(NbProducts, NbPlates, NbPositions, repeat);
}
如果要重復3次,您只需說
recursive(NbProducts, NbPlates, NbPositions, 3);
(警告:僅當您沒有任何函數簽名約束,未指定任何函數約束時,此方法才起作用,所以我認為您沒有)
最簡單,最直接的方法:將其作為參數傳遞,盡管這需要修改函數簽名:
// Start
recursive(par1,par2,par3, 0 /* Iteration number */);
int recursive(int NbProducts, int NbPlates, int NbPositions, int iteration)
{
if(iteration == 2)
return something;
else {
++iteration;
return recursive(par1,par2,par3,iteration);
}
}
或等效地將值減至零。 這也是Prolog和其他邏輯語言在許多情況下限制其遞歸深度的最常用方式。
嘗試這樣的事情:
int arecursive(int NbProducts, int NbPlates, int NbPositions, int count)
{
if (count == 0) {
// ...
{
else
return recursive(NbProducts, NbPlates, NbPositions, count -1);
}
int recursive(int NbProducts, int NbPlates, int NbPositions)
{
arecursive(NbProducts, NbPlates, NbPositions, 3);
}
如果可以更改函數簽名,請將其作為參數傳遞:
int recursive(int NbProducts, int NbPlates, int NbPositions,int repeat) {
return (repeat == 1 ? result : recursive(NbProducts, NbPlates, NbPositions, repeat-1);
}
如果您不能更改簽名,則在功能范圍中需要一個變量來跟蹤它。 成員變量和包裝函數。
int recursive(int NbProducts, int NbPlates, int NbPositions) {
return (m_repeat == 1 ? result : recursive(NbProducts, NbPlates, NbPositions, m_repeat-1);
}
int recursive(int NbProducts, int NbPlates, int NbPositions,int repeat) {
m_repeat = repeat; // setting the member variable repeat before calling the function
recursive(NbProducts, NbPlates, NbPositions);
m_repeat = 0; // just in case
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.