动态规划算法6
LeetCode 279 完全平方数 2023.12.11
- 题目链接
- 代码随想录讲解[链接]
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
dp[0] = 0;
for (int i = 1; i <= sqrt(n); i++)
{
for(int j = i*i; j <= n; j++)
{
dp[j] = min(dp[j-i*i]+1, dp[j]);
}
}
return dp[n];
}
LeetCode 139 单词拆分 2023.12.11
- 题目链接
- 代码随想录讲解[链接]
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.size()+1, false);
dp[0] = true;
string cur;
for (int i = 1; i <= s.size(); i++)
{
for(int j = 0; j <= i; j++)
{
cur = s.substr(j, i-j);
if(find(wordDict.begin(), wordDict.end(), cur) != wordDict.end() && dp[j] == true)
dp[i] = true;
}
}
return dp[s.size()];
}
卡码网 56 携带矿石资源(多重背包) 2023.12.11
- 题目链接
- 代码随想录讲解[链接]
#include<bits/stdc++.h>
using namespace std;
int main()
{
int bagSize, sortSize;
cin >> bagSize >>sortSize;
vector<int> weight(sortSize, 0);
vector<int> price(sortSize, 0);
vector<int> num(sortSize, 0);
for(int i = 0; i < sortSize; i++)
cin >> weight[i];
for(int i = 0; i < sortSize; i++)
cin >> price[i];
for(int i = 0; i < sortSize; i++)
cin >> num[i];
vector<int> dp(bagSize+1, 0);
for(int i = 0; i < sortSize; i++)
{
for(int j = bagSize; j >= weight[i]; j--)
{
for(int k = 1; k <= num[i] && j >= k*weight[i]; k++)
{
dp[j] = max(dp[j-k*weight[i]] + k*price[i], dp[j]);
}
}
}
cout << dp[bagSize] << endl;
return 0;
}