代码随想录45天|322. 零钱兑换、279. 完全平方数

322. 零钱兑换 - 力扣(Leetcode)

class Solution {
public:
    int coinChange(vector& coins, int amount) {
        vector dp(amount + 1, INT_MAX);
        dp[0] = 0;
        for(int i = 0; i < coins.size(); i++) {
            //if(coins[i] <= amount) dp[coins[i]] = 1;
            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);
            }
        }
        return dp[amount] == INT_MAX ? -1 : dp[amount];
    }
};

279. 完全平方数 - 力扣(Leetcode)

class Solution {
public:
    int numSquares(int n) {
        vector dp(n + 1, INT_MAX);
        dp[0] = 0;
        /*for(int i = 1; i * i <= n; i++) {
            dp[i * i] = 1;
        }*/
        int max_square = sqrt(n);
        for(int i = 1; i <= max_square; i++) {
            for(int j = i * i; j < dp.size(); j++) {

                dp[j] = min(dp[j], dp[j - i * i] + 1);
            }
        }
        return dp.back();
    }
};

你可能感兴趣的:(代码随想录,leetcode)