题目描述
- 和完全平方数基本上一样啦,但是我觉得这道题的判断 & 循环处理更恶心
思路 & 代码
- 相对于完全平方数,这里要考虑零钱数组无序,要先进行排序
- 与此同时,还要考虑零钱数组的值并不一定最小为1,因此 dp[i] 不能直接初始化为 i
- 用到临时变量 min,结合对比判断 防止dp[i] 变成 MIN_VALUE(而非直接Math.min())
class Solution {public int coinChange(int[] coins, int amount) {Arrays.sort(coins);int[] dp = new int[amount + 1];for(int i = 1; i <= amount; i++){int min = Integer.MAX_VALUE;for(int j = 0; j < coins.length && i - coins[j] >= 0; j++){if(dp[i - coins[j]] < min){min = dp[i - coins[j]] + 1;}}dp[i] = min;}if(dp[amount] == Integer.MAX_VALUE){return -1;}return dp[amount];}
}
class Solution {public int coinChange(int[] coins, int amount) {Arrays.sort(coins);int[] ans = new int[amount + 1];for(int i = 1; i <= amount; i++) {int min = Integer.MAX_VALUE;for(int j = 0; j < coins.length && i - coins[j] >= 0; j++) {if(ans[i - coins[j]] < min) {min = ans[i - coins[j]] + 1;}}ans[i] = min;}return ans[amount] == Integer.MAX_VALUE ? -1 : ans[amount];}
}