代码随想录算法训练营第四十四天 | 322.零钱兑换 279.完全平方数 139.单词拆分
322.零钱兑换
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// dp[j]: 表示能凑成面额j所需的最少硬币个数
vector<int> dp(amount + 1, 0);
// 递推公式: dp[j] = min(dp[j - coins[i]] + 1, dp[j])
// 初始化
for(int j = 1; j <= amount; ++j) dp[j] = INT_MAX;
for(int j = 0; j <= amount; ++j) {
for(int i = 0; i < coins.size(); ++i) {
if(j >= coins[i] && dp[j - coins[i]] != INT_MAX) dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
for(int val : dp) cout << val << " ";
if(dp[amount] == INT_MAX) return -1;
return dp[amount];
}
};
279.完全平方数
class Solution {
public:
int numSquares(int n) {
// dp[j]: 表示和为j的完全平方数的最小数量为dp[j]
vector<int> dp(n + 1, INT_MAX);
// 递推公式: dp[j] = dp[j - i * i] + 1;
// if(n == int(sqrt(n)) * int(sqrt(n))) return 1;
// 初始化dp[0] = 1;
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> wordSet(wordDict.size());
for(string str : wordDict) wordSet.insert(str);
// dp[j]: 是否能够凑成长度为j的字符串
vector<int> dp(s.size() + 1, false);
// 递推公式 d[j] = dp[j - wordDict[i].size()]
// 初始化
dp[0] = true;
for(int i = 1; i <= s.size(); ++i) { // 遍历背包
for(int j = 0; j <= i; ++j) { // 遍历物品
string word = s.substr(j, i - j);
if(wordSet.find(word) != wordSet.end() && dp[j] == true)
dp[i] = true;
}
}
return dp[s.size()];
}
};
分类:
代码随想录
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端