标签:
-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: Constructing the solution in the order of sum. ( Get 1, 2, ..., amount)
class Solution { public int coinChange(int[] coins, int amount) { if (amount < 1) return 0; int[] dp = new int[amount + 1]; int sum = 0; while (++sum <= amount) { //constructing the result from 1,2..., amount int min = -1; // -1 means cannot get this amount. for (int coin : coins) { if (sum >= coin && dp[sum - coin] != -1) { int tempSolution = dp[sum - coin] + 1; if (min == -1) min = tempSolution; //initialize solution. else min = Math.min(tempSolution, min); } } dp[sum] = min; } return dp[amount]; } }
DP: Constructing the solution by how many coins used. ( Use 1 coin, use 2 coins, ... until the target is reached.)
public class Solution { public int coinChange(int[] coins, int amount) { if(amount == 0) return 0; int len = amount+1; int[] result = new int[len]; result[0] = 0; List<Integer> q = new ArrayList<Integer>(); int minimumCoins = 1; for(Integer c : coins) { if(c < len) { result[c] = minimumCoins; q.add(c); } } while(!q.isEmpty()) { ++minimumCoins; if(result[amount] != 0) return result[amount]; List<Integer> next = new ArrayList<Integer>(); for(Integer c : coins) { for(Integer optimal: q) { int sum = c+optimal; if(sum < len && result[sum] == 0) { //Find the new numbers that you can get with minimumCoins coins. //Add one more coin to these numbers, //you can get the next group of those optimial numbers. result[sum] = minimumCoins; next.add(sum); } } } q = next; } return -1; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5562643.html