1 class Solution { 2 public int change(int amount, int[] coins) { 3 if (amount == 0) { 4 return 1; 5 } 6 if(coins == null || coins.length == 0){ 7 return 0; 8 } 9 int[] dp = new int[amount + 1]; 10 dp[0] = 1; 11 for (int coin : coins) { 12 for (int i = coin; i <= amount; i++) { 13 dp[i] += dp[i - coin]; 14 } 15 } 16 return dp[amount]; 17 } 18 }
对比leetcode322:
1 public class Solution { 2 public int coinChange(int[] coins, int amount) { 3 if (amount == 0) return 0; 4 int[] dp = new int[amount + 1]; 5 dp[0] = 0; 6 for (int i = 1;i <= amount ;i++ ) { 7 dp[i] = Integer.MAX_VALUE; 8 for(int k :coins) { 9 if(i>=k && dp[i-k] != Integer.MAX_VALUE) { 10 dp[i] = Math.min(dp[i-k] + 1,dp[i]); 11 } 12 } 13 } 14 if(dp[amount]<Integer.MAX_VALUE && dp[amount] > 0) { 15 return dp[amount]; 16 } else { 17 return -1; 18 } 19 20 } 21 }