我已经读过,贪心算法仅照顾当时试图达到的最佳解决方案,但这是否是我要创建贪心算法时应该考虑的唯一标准? 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, lenCoinSet, money)<<endl; return 0; }
而且我认为这很贪婪,但我不确定。如果您能解释我编写的代码是否贪婪,我将不胜感激。此外,如果不是,您是否可以分享其他可能的解决方案,或者可能有一些建议来改进此代码?最后,如果有文档可以推荐我,我将非常感谢。
我已经读过一个贪婪算法只关心当时试图达到的最佳解决方案,但是如果我想创建一个贪婪,这是我应该考虑的唯一标准...