我創建一個程序,它返回它完美對於n值很小隻使用1,2,6和13得到一個數(n)所需資金的數量最少,但一旦n得到的值爲200,這會讓程序花費太多時間來計算結果。優化遞歸函數
因此,我有兩個問題:
有沒有什麼辦法讓遞歸更快?
2.我應該避免使用遞歸和使用循環呢?
這裏的註釋代碼:
#include <iostream>
#define MAX 500000
using namespace std;
void cal(int inp, int &mini, int counter = 0);
int main (void)
{
//Gets input
int n;
cin >> n;
//Defines mini as the MAX result we can get
int mini = MAX;
//Calls the function
cal(n, mini);
//Prints the best result
cout << mini << endl;
return 0;
}
void cal(int inp, int &mini, int counter)
{
//Breaks recursion if it finds an answer
if(!inp)
{
if(counter<mini) mini = counter;
return;
}
//Breaks recursion if the input is negative
//or the counter is more than the best result
else if((inp<0) || (counter>mini)) return;
//Counts amount of recursions
counter++;
//Tries every combination
cal(inp-13, mini, counter);
cal(inp-6, mini, counter);
cal(inp-2, mini, counter);
cal(inp-1, mini, counter);
return;
}
謝謝
循環幾乎總是快於遞歸。 – freakish
性能問題不是因爲遞歸。這是因爲你的蠻力算法。 –
您需要一個漸近較好的算法,而不是微觀優化。 –