您的位置:首页 > 其它

322. Coin Change

2018-01-06 14:52 274 查看

322. 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
.

题目大意:给定一个硬币数组,给定amount,问使用硬币数组中的硬币,找出能组成amount的最少的硬币数。

思路:dp.dp[i]表示组成i元钱需要的最少的硬币的个数。

代码

package DP;

import java.util.Arrays;

/**
* @author OovEver
* 2018/1/6 14:41
*/
public class LeetCode322 {
public static int coinChange(int[] coins, int amount) {
if (amount == 0) {
return 0;
}
for (int i=0;i<coins.length;i++) {
if (coins[i] == amount) {
return 1;
}
}
//        dp[i]表示组成i元钱需要的最少的硬币的个数
int[] dp = new int[amount + 1];
for(int i=0;i<coins.length;i++) {
if (coins[i] <= amount) {
dp[coins[i]] = 1;
}
}
for(int i=0;i<coins.length;i++) {
for(int j=coins[i];j<=amount;j++) {
if (dp[j] != 0 && dp[j - coins[i]] != 0) {
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
} else if (dp[j - coins[i]] != 0) {
dp[j] = dp[j - coins[i]] + 1;
}
}
}
if (dp[amount] == 0) {
return -1;
}
return dp[amount];
}

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