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

322. 零钱兑换

c++ 复制代码
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. 完全平方数

c++ 复制代码
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. 单词拆分

c++ 复制代码
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()];
    }
};
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼6 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光6 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark6 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her16 天前
并查集-听课笔记
笔记·算法·并查集
码流子6 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven6 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark6 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218616 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法