给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
 输出: 3 
 解释: 11 = 5 + 5 + 1
 示例 2:
输入: coins = [2], amount = 3
 输出: -1
 说明:
 你可以认为每种硬币的数量是无限的。
思路:每一个数据都可以看做前面某一个dp[x]加上一个coins[i]的值,如果找不到这样的数字,那说明无法进行兑换
提交的代码:
class Solution {
     public int coinChange(int[] coins, int amount) {
      int i,j;
         Arrays.sort(coins);
         int n = coins.length;
         int[] dp = new int[amount+1];
         int min = Integer.MAX_VALUE;
         dp[0] = 0;
         if(amount==0)
         {
             return 0;
         }
         for(i=1;i<=amount;i++)
         {
             min = Integer.MAX_VALUE;
             for(j=0;j<n;j++)
             {
                 if(i-coins[j]>=0)
                 {
                     if(dp[i-coins[j]] != Integer.MAX_VALUE)
                     {
                         min = java.lang.Math.min(min, dp[i-coins[j]]+1);
                     }
                }
                 else
                 {
                     break;
                 }
             }
             dp[i] = min;
         }
         if(dp[amount]!=Integer.MAX_VALUE)
         {
              return dp[amount];
         }
         else
         {
             return -1;
         }
     }
 }
完整的代码:
import java.util.Arrays;
public class Solution322 {
     public static int coinChange(int[] coins, int amount) {
         int i,j;
         Arrays.sort(coins);
         int n = coins.length;
         int[] dp = new int[amount+1];
         int min = Integer.MAX_VALUE;
         dp[0] = 0;
         if(amount==0)
         {
             return 0;
         }
         for(i=1;i<=amount;i++)
         {
             min = Integer.MAX_VALUE;
             for(j=0;j<n;j++)
             {
                 if(i-coins[j]>=0)
                 {
                     if(dp[i-coins[j]] != Integer.MAX_VALUE)
                     {
                         min = java.lang.Math.min(min, dp[i-coins[j]]+1);
                     }
                }
                 else
                 {
                     break;
                 }
             }
             dp[i] = min;
         }
         if(dp[amount]!=Integer.MAX_VALUE)
         {
              return dp[amount];
         }
         else
         {
             return -1;
         }
     }
     public static void main(String[] args)
     {
         int[] coins = {186,419,83,408};
         int amount = 6249;
         System.out.println(coinChange(coins,amount));
     }
 }