1、题目描述
2、代码详解
python版
class Solution(object):
def coinChange(self, coins, amount):
"""
此函数用于解决硬币找零问题,通过动态规划的方法找出凑出指定金额所需的最少硬币数量。
:param coins: 一个列表,包含不同面额的硬币
:param amount: 一个整数,表示需要凑出的总金额
:return: 凑出指定金额所需的最少硬币数量,如果无法凑出则返回 -1
"""
# 初始化一个最大值,表示无法凑出该金额
MAX = float('inf')
# 创建一个长度为 amount + 1 的列表 dp,用于存储凑出每个金额所需的最少硬币数量
# 初始值都设为 MAX,表示暂时无法凑出这些金额
dp = [MAX] * (amount + 1)
# 凑出金额 0 不需要任何硬币,所以 dp[0] 设为 0
dp[0] = 0
# 遍历从 1 到 amount 的每个金额
for i in range(1, amount + 1):
# 遍历每种硬币面额
for coin in coins:
# 只有当当前金额 i 大于等于硬币面额 coin,并且 dp[i - coin] 不是 MAX 时
# 才说明可以使用该硬币来凑出金额 i
if i >= coin and dp[i - coin] != MAX:
# 更新 dp[i] 为当前值和 dp[i - coin] + 1 中的较小值
# dp[i - coin] + 1 表示使用当前硬币后所需的最少硬币数量
dp[i] = min(dp[i], dp[i - coin] + 1)
# 如果 dp[amount] 仍然是 MAX,说明无法用给定的硬币凑出该金额,返回 -1
if dp[amount] == MAX:
return -1
# 否则返回凑出该金额所需的最少硬币数量
return dp[amount]
- 时间复杂度:(O(amount * len(coins))),其中
amount
是需要凑出的总金额,len(coins)
是硬币面额的数量。 - 空间复杂度:(O(amount)),主要用于存储
dp
数组。
class Solution(object):
def coinChange(self, coins, amount):
# 不同面额的硬币 coins 和一个总金额 amount
MAX = float('inf')
dp = [MAX for i in range(amount+1)]
dp[0] = 0
for i in range(1, amount+1):
for coin in coins: # 依次取不同的币值
# 写法1
# if i - coin < 0:
# continue # 跳出取coin的循环
# dp[i] = min(dp[i], dp[i-coin]+1)
# 写法2
if i >= coin and dp[i-coin] != MAX:
dp[i] = min(dp[i], dp[i-coin]+1)
if dp[amount] == MAX: # max时表示无法用硬币拼出amount
return -1
return dp[amount]
amount = 11
coins = [1, 2, 5]
s = Solution()
print(s.coinChange(coins, amount))
九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
java版
public class coinChange322 {
public static void main(String[] args){
int[] coins = {1, 2, 5};
int amount = 11;
System.out.println(coinChange(coins, amount));
}
public static int coinChange(int[] coins, int amount){
// 数组大小为 amount + 1,初始值也为 amount + 1
int max = amount + 1;
int[] dp = new int[amount+1];
// base case
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 0; i <= amount; i++) {//0,<不行,注意边界条件
// 内层 for 在求所有子问题 + 1 的最小值
for (int coin : coins) {
// 子问题无解,跳过
if (i - coin < 0) continue;
dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
}
// for (int j = 0; j < coins.length; j++) {
// if (coins[j] <= i) {
// dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
// }
}
return (dp[amount] > amount) ? -1 : dp[amount];
}
}
DP法和DFS+greedy+pruning法