【代码随想录Day45】动态规划

70 爬楼梯 (进阶)

https://leetcode.cn/problems/climbing-stairs/

class Solution {  //每次1-m级,完全背包的做法
    public int climbStairs(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        int m = 2;
        for (int i = 1; i <= n; i++) { //外层循环总台阶数
            for (int j = 1; j <= m; j++) {  //内层循环每次可走的台阶数
                if(i >= j) dp[i] += dp[i - j];
            }
        }
        return dp[n];
    }
}

322 零钱兑换 (纯完全背包)

https://leetcode.cn/problems/coin-change/

钱币有顺序和没有顺序都可以,都不影响钱币的最小个数。两种循环谁在外谁在里都可以。

class Solution { // 外coin内amount
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE / 2);
        dp[0] = 0;
        for (int coin : coins) {
            for (int i = coin; i <= amount; i++) {
                dp[i] = Math.min(dp[i], dp[i - coin] + 1);
            }
        }
        return dp[amount] >= Integer.MAX_VALUE / 4 ? -1 : dp[amount];
    }
}

class Solution {   // 外amount内coin
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE / 2);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int coin : coins) {
                if (i - coin >= 0) {
                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                }
            }
        }
        return dp[amount] >= Integer.MAX_VALUE / 4 ? -1 : dp[amount];
    }
}

279 完全平方数

https://leetcode.cn/problems/perfect-squares/ 同样两种循环顺序都可以

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; i++) {
            for (int sum = i * i; sum <= n; sum++) {
                dp[sum] = Math.min(dp[sum - i * i] + 1, dp[sum]);
            }
        }
        return dp[n];
    }
}

你可能感兴趣的:(代码随想录,算法,leetcode,动态规划)