LeetCode37● 70. 爬楼梯 (进阶)● 322. 零钱兑换 ● 279.完全平方数

322. 零钱兑换

class Solution {
    public int coinChange(int[] coins, int amount) {
        //容量 amount
        //dp[j] 凑齐面额j需要的最少硬币个数
        //dp[j] = min(dp[j],dp[j - coins[i]] + 1)
        //dp[0] = 0;others max int
        int[] dp = new int[amount + 1];
        dp[0] = 0;
        for(int i = 1;i <= amount;i++){
            dp[i] = Integer.MAX_VALUE;
        }
        for(int i = 0;i < coins.length;i++){
            for(int j = coins[i];j <= amount;j++){
                //这里如果dp[j - coins[i] = max,再加一就溢出了]
                if(dp[j - coins[i]] != Integer.MAX_VALUE)
                dp[j] = Math.min(dp[j],dp[j - coins[i]] + 1);
            }
        }
        if(dp[amount] == Integer.MAX_VALUE)return -1;
        return dp[amount];
    }
}

279.完全平方数 

class Solution {
    public int numSquares(int n) {
        //dp[j] 和为j的最小完全平方数的数量时dp[j]
        //物品 1 ~ n
        //dp[j] = min(dp[j],dp[j - i * i] + 1)
        //dp[0] = 0, other max
        int[] dp = new int[n + 1];
        int max = Integer.MAX_VALUE;
        for(int i = 0;i < dp.length;i++){
            dp[i] = max;
        }
        dp[0] = 0;
        for(int i = 1; i <= n;i++){
            for(int j = i;j <=n;j++){
                if(j - i * i >= 0 && dp[j - i * i] != max)
                dp[j] = Math.min(dp[j],dp[j - i * i] + 1);
            }
        }
        return dp[n];
    }
}

你可能感兴趣的:(算法,leetcode,职场和发展)