算法训练营笔记day45|70. 爬楼梯、322. 零钱兑换、279. 完全平方数

70. 爬楼梯

题目连接

笔记

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

322. 零钱兑换

题目连接

笔记

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

279. 完全平方数

题目连接

笔记

class Solution {
public:
    int numSquares(int n) {
        vector<int> nums;
        for (int i = 1; i <= sqrt(n); i++) {
            nums.push_back(i * i);
        }
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = nums[i]; j <= n; j++) {
                    dp[j] = min(dp[j], dp[j - nums[i]] + 1);
            }
        }
        return dp[n];
    }
};

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