代码随想录算法训练营第45天|70. 爬楼梯、322. 零钱兑换、279.完全平方数

70. 爬楼梯

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

用dp数组

class Solution {
public:
    int climbStairs(int n) {
        vector dp(n + 1, 0);
        dp[0] = 1;
        for (int j = 0; j <= n; j++) {
            for (int i = 1; i <= 2; i++) {
                if (j >= i && dp[j] < INT_MAX - dp[j - i]) dp[j] += dp[j - i];
            }
        }
        return dp.back();
    }
};

322. 零钱兑换

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

class Solution {
public:
    int coinChange(vector& coins, int amount) {
        vector dp(amount + 1, -1);
        dp[0] = 0;
        for (int i = 0; i < coins.size(); i++) {
            for (int j = coins[i]; j <= amount; j++) {
                if (dp[j - coins[i]] != -1) {
                    dp[j] = dp[j] == -1 ? dp[j - coins[i]] + 1 : min(dp[j], dp[j - coins[i]] + 1); 
                }
            }
        }
        return dp[amount];
    }
};

279.完全平方数

https://leetcode.cn/problems/perfect-squares/

class Solution {
public:
    int numSquares(int n) {
        int m = (int)sqrt(n);
        vector dp(n + 1, 0);
        for (int j = 0; j <= n; j++) dp[j] = j;
        for (int i = 2; i <= m; i++) {
            for (int j = (int)pow(i, 2); j <= n; j++) {
                dp[j] = min(dp[j], dp[j - (int)pow(i, 2)] + 1);
            }
        }
        return dp.back();
    }
};

 

 

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