单词拆分
class Solution {
/*
s: 背包;
s.size():背包容量;
wordDict:物品;
wordDict.size():物品种类;
完全背包问题;
物品有唯一的装填顺序,要找出所有的组合顺序,外层for循环需要遍历背包;
*/
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);
if(wordSet.find(word) != wordSet.end() && dp[j]){
dp[i] = true;
}
}
}
return dp[s.size()];
}
};