原题网址:https://leetcode.com/problems/coin-change/
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
方法:动态规划。
public class Solution {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
if (amount < 0) return -1;
int[] nums = new int[amount+1];
for(int i=0; i<coins.length; i++) {
if (coins[i] <= amount) nums[coins[i]] = 1;
}
for(int i=1; i<amount; i++) {
if (nums[i]==0) continue;
for(int j=0; j<coins.length; j++) {
if (i+coins[j] <= amount && (nums[i+coins[j]] == 0 || nums[i] + 1 < nums[i+coins[j]])) nums[i+coins[j]] = nums[i] + 1;
}
}
if (nums[amount] == 0) return -1;
return nums[amount];
}
}
另一种实现:
public class Solution {
public int coinChange(int[] coins, int amount) {
int[] nums = new int[amount+1];
Arrays.fill(nums, -1);
nums[0] = 0;
for(int i=0; i<amount; i++) {
if (nums[i] == -1) continue;
for(int j=0; j<coins.length; j++) {
int k = i+coins[j];
if (k<=amount && (nums[k]==-1 || nums[i]+1<nums[k])) nums[k] = nums[i]+1;
}
}
return nums[amount];
}
}

本文介绍如何使用动态规划解决硬币找零问题,给出两种实现方式,包括算法思路、代码实现及实例解析。
&spm=1001.2101.3001.5002&articleId=51239550&d=1&t=3&u=cb7483aa34e54ef09f410d46940679b9)
2252

被折叠的 条评论
为什么被折叠?



