baike 2019-12-23
为了减少重复的递归调用,我们可以反过来计算。先计算f(2),有了f(2)再计算f(3),以此类推,计算到f(n)。在此过程中不需要任何递归
void makechange( int coins[ ], int differentCoins, int maxChange, int coinUsed[] ) { coinUsed[0] = 0; for (int cents = 1; cents <= maxChange; cents++) { //cents为待找零的零钱数额,从1分到所求的maxChange分 int minCoins = cents; for (int j = 1; j < differentCoins; j++) { if (coins[j] > cents) continue; if (coinUsed[ cents - coins[j] ] + 1 < minCoins) minCoins = coinUsed[ cents - coins[j] ] + 1; } coinUsed[cents] = minCoins; //Coins存放所有不同的硬币值,不同的硬币个数为differentCoins。 } }