1.零钱兑换
1.1 题目
https://leetcode.cn/problems/coin-change/description/
1.2 题解
class Solution {
public:
int coinChange(vector<int>& coins, int amount)
{
//确定dp数组,dp[j]表示凑成总金额j的最少硬币数为dp[j]
vector<int> dp(amount + 1, INT_MAX);
//确定递推逻辑
//dp[j]=min(dp[j],dp[j-coins[i]]+coins[i];
//初始化
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 - coins[i]]是初始值则跳过
{
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
}
return dp[amount] == INT32_MAX ? -1 : dp[amount];
}
};
2.完全平方数
2.1 题目
https://leetcode.cn/problems/perfect-squares/description/
2.2 题解
class Solution
{
public:
int numSquares(int n)
{
//确定dp数组,dp[j]表示的是和为j的完全平方数的和的最小数量
vector<int> dp(n + 1, INT32_MAX);
//确定递推逻辑
//d[j]=min(d[j],d[j-i*i]+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], dp[j - i * i] + 1);
}
}
return dp[n];
}
};
3.单词拆分
3.1 题目
https://leetcode.cn/problems/word-break/description/
3.2 题解
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict)
{
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
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); //substr(起始位置,截取的个数)
if (wordSet.find(word) != wordSet.end() && dp[j]) {
dp[i] = true;
}
}
}
return dp[s.size()];
}
};