image.png

解决思路

动态规划

image.png
image.png
image.png

code

  1. public int coinChange(int[] coins, int amount) {
  2. int max = amount + 1;
  3. int[] dp = new int[amount + 1];
  4. Arrays.fill(dp, max);
  5. dp[0] = 0;
  6. for (int i = 1; i <= amount; i++) {
  7. for (int j = 0; j < coins.length; j++) {
  8. if (coins[j] <= i) {
  9. dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
  10. }
  11. }
  12. }
  13. return dp[amount] > amount ? -1 : dp[amount];
  14. }