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];
}
};
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];
}
};
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()];
}
};