leetcode 322. Coin Change 解题思路 C语言

本文详细解析了硬币找零问题的解决方法,通过动态规划算法实现了计算组成特定金额所需的最少硬币数量。适用于无限数量的硬币类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


这道题刚开始拿到的时候,没有什么思路,参考了一下网上别人的思路。很多人就说dp算法和BFS算法去解这道题。但是我是个菜鸟啊。我根本就不懂什么是dp算法啊。然后代码也没有啥注释根本就看不懂啊。然后我就自己去研究了一下代码和DP算法。

DP算法说通俗一点 就是大事化小事,然后循环或者递归处理它。具体的思路网上也有讲,都感觉比较复杂而且比较抽象。针对这道题我们的思路就是如果我们传一个不定值得amount,还用同样的数组去组合怎么得到解。我们比较好理解的就是从1开始然后+1,这样迭代上去,都用同一套规则来判断。这个部分算是一个提示,帮助大家好独立思考完成题目。下面具体讲一下每一步的思路和代码。

int com(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int coinChange(int* coins, int coinsSize, int amount) 
{
int i, j, n = 0;
int nVal;
//首先申请一个和amount+1一样大的数组Array,表示从0-amount遍历全部情况。
int *array = (int*)malloc(sizeof(int)*(amount+1));
//这里要给coins从小到大排序一下
qsort(coins, coinsSize, sizeof(int), com);
//0的情况就是不需要组合  所以可以给Array[0] = 0。
array[0] = 0;
//后后面的思路就是 遍历全部Array数组, i 就是对应的要通过硬币组合出来的数字,Array[i]对应的就是存要的硬币的最小值。
for (i = 1 ; i < amount+1; ++i)
{
//先给每个里面付初始值amount+1,。
array[i] = amount+1;
//然后对应的遍历所有的coins数组。
for (j = 0; j < coinsSize && coins[j] <= i; ++j)
{
//当coins[j] == i的时候则Array[i] = 1。这表示这个数只要一个元素组成。
if (coins[j] == i)
{
array[i] = 1;
break;
}
//当i减去当前的一个元素 ,得到一个新值,查看一下这个值在之前有没有组成的最小数
nVal = i - coins[j];
//-1表示当前的coins中的元素无法组成这个数
if (array[nVal] != -1 && array[nVal] + 1 < array[i])
{
array[i] = array[nVal] + 1;
}
}
//遍历玩coins中的值  如果array[i]的值没有改变它的初值的话就说明无法组成这个数
if (array[i] == amount + 1)
{
array[i] = -1;
}
}
return array[amount];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值