题目描述:
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
示例 2:
输入:coins = [2], amount = 3
输出:-1
示例 3:
输入:coins = [1], amount = 0
输出:0
示例 4:
输入:coins = [1], amount = 1
输出:1
示例 5:
输入:coins = [1], amount = 2
输出:2
提示:
1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104
代码:
public class LC322 {
//时间复杂度O(amount*coins.Length)
//空间复杂度O(n)
//dp,dp[i]用来存取当总金额为i时,所需要的最少硬币数
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 10];
//初始化
Arrays.fill(dp,Integer.MAX_VALUE - 1000);
//总金额为0的时候,只需要0个硬币
dp[0] = 0;
//求1~amount-1的最少硬币数,从而得出amout的最少硬币数
for (int i = 1;i <= amount; i++){
for (int j = 0; j < coins.length; j++){
//如果当前amount比当前硬币面值大,就可以换
if (i >= coins[j]){
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
}
}
}
//如果遍历完,还为初始化值就代表无法换为合适的
if (dp[amount] < Integer.MAX_VALUE - 1000){
return dp[amount];
}else {
return -1;
}
}
public static void main(String[] args) {
LC322 obj = new LC322();
System.out.println(obj.coinChange(new int[]{2,4,5}, 11));
}
}

本文介绍了一种解决硬币找零问题的算法,通过动态规划的方法计算出组成特定金额所需的最少硬币数量。该算法的时间复杂度为O(amount * coins.Length),空间复杂度为O(n)。
6万+

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



