代码实现:
#define min(a, b) ((a) > (b) ? (b) : (a))int coinChange(int *coins, int coinsSize, int amount) {int dp[amount + 1];// 初始化for (int i = 0; i < amount + 1; i++) {dp[i] = INT32_MAX;}dp[0] = 0;// 01背包 -----先遍历物品,再遍历背包// for (int i = 0; i < coinsSize; i++) { // 遍历物品// for (int j = coins[i]; j <= amount; j++) { // 遍历背包// if (dp[j - coins[i]] != INT32_MAX) { // 如果dp[j - coins[i]]是初始值则跳过// dp[j] = min(dp[j - coins[i]] + 1, dp[j]);// }// }// }// 01背包 -----先遍历背包,再遍历物品for (int j = 0; j <= amount; j++) { // 遍历背包for (int i = 0; i < coinsSize; i++) { // 遍历物品if (j >= coins[i] && dp[j - coins[i]] != INT32_MAX) { // 如果dp[j - coins[i]]是初始值则跳过dp[j] = min(dp[j - coins[i]] + 1, dp[j]);}}}if (dp[amount] == INT32_MAX) {return -1;}return dp[amount]; }