我已经读到,贪心算法只关心当时试图达到的最佳解决方案,但是如果我要创建贪心算法,这是我应该考虑的唯一标准吗? Aslo,我怎么知道我是否创建了贪婪算法?我的意思是,我为C++
中的 change 问题创建了以下代码:
#include <iostream>
using namespace std;
int greedyChange(int coinSet[],int lenCoinSet,int money){
int change = 0;
static int i = 0;
if(i >= lenCoinSet){
return 0;
}
while(money - coinSet[i] >= 0){
change++;
money -= coinSet[i];
}
i++;
return change + greedyChange(coinSet,lenCoinSet,money);
}
int main(int argc,char const *argv[]){
int coinSet[]={20,15,10,5,1};
int lenCoinSet = sizeof(coinSet)/sizeof(coinSet[0]);
int money = 30;
cout << "The minimun number of coins to get your change is: "
<< greedyChange(coinSet,money)<<endl;
return 0;
}
我认为这很贪婪,但我不确定。如果您能解释我编写的代码是否贪婪,我将不胜感激。此外,如果不是,您是否可以分享其他可能的解决方案,或者可能有一些建议来改进此代码?最后,如果有文档可以推荐我,我将非常感谢。