原题链接:https://leetcode-cn.com/problems/coin-change/
class Solution { public int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; // 初始化 // fill() 用法 /** int[] a = new int[]{1,2,3,4,5,6}; System.out.println(Arrays.toString(a)); //{1,2,3,4,5,6} Arrays.fill(a, 0); System.out.println(Arrays.toString(a)); //{0,0,0,0,0,0} int[] b = new int[]{1,2,3,4,5,6}; Arrays.fill(b, 2, 4, 0); System.out.println(Arrays.toString(b)); //{1,2,0,0,5,6} **/ Arrays.fill(dp, amount + 1); dp[0] = 0; // dp[i] = k 表示i元时,需要k个硬币 for (int i = 1; i <= amount; i++){ for (int j = 0; j < coins.length; j++){ if (coins[j] <=i){ // i元需要的硬币个数为 i减去其中一个硬币值后后再加一个硬币的个数 然后取最小的那个 dp[i] = Math.min(dp[i],dp[i-coins[j]] + 1); } } } return dp[amount] > amount?-1:dp[amount]; } }
难点:
1 Arrays.fill() 用法记住
2 状态转移方程式:
dp[i] = Math.min(dp[i],dp[i-coins[j]] + 1);