算法随想录算法训练营第三十九天|70. 爬楼梯 (进阶) 322. 零钱兑换 279.完全平方数

70. 爬楼梯 (进阶)

思路:爬楼梯因为你每次可以爬一阶或者是两阶,所以你爬第n阶楼梯的方法应该是第n-1阶和n-2阶楼梯方法的总和。

class Solution {
    public int climbStairs(int n) {
       int[] dp = new int[n+1];
       dp[0] = 1;
       dp[1] = 1;
       for(int i = 2;i<= n;i++){
           dp[i] = dp[i-1]+dp[i-2];
       }
       return dp[n];
    }
}

322. 零钱兑换 

class Solution {
    public int coinChange(int[] coins, int amount) {
      int max = Integer.MAX_VALUE;
        int[] dp = new int[amount + 1];
        dp[0] = 0;
        for (int i = 1; i < amount + 1; i++) {
            dp[i] = max;
        }
        for (int i = 0; i < coins.length; i++) {//先遍历物品
            for (int j = 0; j <= amount; j++) {//在遍历背包容量
                if (j < coins[i])
                    dp[j] = dp[j];
                else if (dp[j - coins[i]] != max)
                    dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
            }
        }
        if (dp[amount] == max)
            return -1;
        return dp[amount];
    }
}

279.完全平方数 

class Solution {
    public int numSquares(int n) {
        if(n == 1)
            return 1;
       int[][] dp = new int[n/2+1][n + 1];
        for (int i = 0; i <= n; i++) {
            dp[1][i] = i;
        }
        for (int i = 2; i <= n/2; i++) {
            for (int j = 1; j <= n; j++) {
                if (j < i * i) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] =  Math.min(dp[i][j - i * i] + 1,dp[i-1][j]);
                }
            }
        }
        int res = Integer.MAX_VALUE;
        for(int i = 1;i<=n/2;i++){
            res = Math.min(res,dp[i][n]);
        }
        return res;
    }
}

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