1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class Solution { int res = Integer.MAX_VALUE; public int coinChange(int[] coins, int amount) { if(coins.length == 0){ return -1; } findways(coins, amount, 0); if(res == Integer.MAX_VALUE){ return -1; } return res; }
public void findways(int[] coins, int amount, int count){ if(amount < 0) return; if(amount == 0){ res = Math.min(count, res); } for(int i = 0; i < coins.length; i++){ findways(coins, amount-coins[i], count+1); } } }
class Solution { int[] memo; public int coinChange(int[] coins, int amount) { if(coins.length == 0){ return -1; } memo = new int[amount]; return findways(coins, amount); }
public int findways(int[] coins, int amount){ if(amount < 0) return -1; if(amount == 0) return 0; if(memo[amount-1] != 0){ return memo[amount-1]; }
int min = Integer.MAX_VALUE; for(int i = 0; i < coins.length; i++){ int res = findways(coins, amount-coins[i]); if(res >= 0 && res < min){ min = res + 1; } } memo[amount - 1] = (min == Integer.MAX_VALUE ? -1 : min); return memo[amount-1]; } }
class Solution { public int coinChange(int[] coins, int amount) { int max = amount + 1; int[] dp = new int[amount+1]; Arrays.fill(dp, max); dp[0] = 0; for(int i = 1; i <= amount; i++){ for(int j = 0; j < coins.length; j++){ if(coins[j] <= i){ dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); } } } return dp[amount] > amount ? -1 : dp[amount]; } }
|