322.CoinChange
Example 1:
Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3 Output: -1
Example 3:
Input: coins = [1], amount = 0 Output: 0
Note:
You may assume that you have an infinite number of each kind of coin.
ans[i]表示凑齐钱数i时需要的最小零钱数目
和题目494类似,
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1); // 初始化dp数组,初始值设为amount+1,保证后续更新时能正确找到最小值
dp[0] = 0; // 金额为0时不需要硬币
for (int i = 0; i < coins.length; i++) {
for (int j = 1; j <= amount; j++) {
if (coins[i] <= j) {
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1); // 更新最少硬币数量
}
}
}
return dp[amount] == amount + 1 ? -1 : dp[amount]; // 如果无法凑成金额,则返回-1,否则返回结果
}
浙公网安备 33010602011771号