【LeetCode】Coin Change(Java)
阿新 • • 發佈:2019-01-04
換錢幣這道題我一開始用回溯法解題,導致超時,後看到提示,改用動態規劃解
這個是動態規劃寫的答案
2017/3/17public class Solution { int min = -1; public int coinChange(int[] coins, int amount) { if(amount == 0) return 0; int key = amount; int[] money = new int[amount+1]; Arrays.fill(money,-1); Arrays.sort(coins); for(int i = 0;i < coins.length;i++){ if(coins[i] > amount) break; money[coins[i]]=1; } int coin = coins[0]; while(coin <= amount){ if(money[coin] == -1){ int min = Integer.MAX_VALUE; int check = 0; for(int j = 0;j < coins.length;j++){ if(coin - coins[j] <= 0) break; if(money[coin - coins[j]] != -1&&money[coin - coins[j]]+1 < min){ min = money[coin - coins[j]]+1; check = 1; } } if(check == 1){ money[coin] = min; //System.out.println(min); } } coin++; } return money[amount]; } }