您的位置:首页 > 编程语言 > C语言/C++

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

2016-03-31 21:10 966 查看
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];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c leetcode