Day48.算法训练

322. 零钱兑换

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];

        Arrays.fill(dp, amount + 1);
        dp[0] = 0;

        for (int coin : coins) {
            for (int j = coin; j < amount + 1; j++) {
                dp[j] = Integer.min(dp[j], dp[j - coin] + 1);
            }
        }
        return dp[amount] <= amount ? dp[amount] : -1;
    }
}

279. 完全平方数

class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n + 1];
        Arrays.fill(dp, n);
        dp[0] = 0;

        for (int i = 1; i * i < n + 1; i++) { // 物品

            for (int j = i * i; j < n + 1; j++) { //背包
                dp[j] = Integer.min(dp[j], dp[j - i * i] + 1);
            }
        }
        return dp[n];
    }
}

你可能感兴趣的:(算法)