leetcode打卡#day46 322. 零钱兑换、279. 完全平方数、139. 单词拆分

322. 零钱兑换

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        //min count
        vector<int> dp(amount+1, INT_MAX);
        int n = coins.size();
        //init
        dp[0] = 0;
        //不包含顺序, 先物品再容量
        for (int i = 0; i < n; 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) {
        //dp 和为i的完全平方数的最少数量
        vector<int> dp(n+1, INT_MAX);
        dp[0] = 0;
        //没有顺序,先物品再容量
        for (int i = 1; i*i <= n; i++) {
            for (int j = i*i; j <= n; j++ ) {
                dp[j] = min(dp[j - i*i]+1, dp[j]);
            }
        }
        return dp[n];
    }
};

139. 单词拆分

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> words(wordDict.begin(), wordDict.end());
        vector<bool> dp(s.length()+1, false);
        dp[0] = true;
        //有顺序,先容量再物品
        for (int i = 0; i <= s.size(); i++) {
            for (int j = 0; j < i; j++) {
                //取字串
                string str = s.substr(j, i - j);
                //若存在, 则返回true
                if (words.find(str) != words.end() && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[s.size()];
    }
};

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-15 15:26:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-15 15:26:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-15 15:26:02       87 阅读
  4. Python语言-面向对象

    2024-06-15 15:26:02       96 阅读

热门阅读

  1. Hive 面试题(七)

    2024-06-15 15:26:02       25 阅读
  2. 搜索文档的好助手

    2024-06-15 15:26:02       37 阅读
  3. js中reduce方法是什么

    2024-06-15 15:26:02       71 阅读
  4. 【react】react 使用 Context 的简单示例

    2024-06-15 15:26:02       27 阅读
  5. 科技创新对农业发展的影响

    2024-06-15 15:26:02       30 阅读
  6. 在 npm 上发布包 npm publish

    2024-06-15 15:26:02       29 阅读
  7. Ollama部署的模型,怎么被调用

    2024-06-15 15:26:02       30 阅读
  8. Notepad++ 使用正则表达式删除空行空格方法

    2024-06-15 15:26:02       31 阅读
  9. btstack协议栈实战篇--LE Peripheral - Delayed Response

    2024-06-15 15:26:02       33 阅读
  10. springmvc 多事务提交和回滚

    2024-06-15 15:26:02       27 阅读