没看答案,动态规划-完全背包问题。
from collections import defaultdict
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
'''
basecase: dp[0]=True表示背包重量为0时不拿物品也符合。
state: dp[i]表示s[0:i]能否拼接出来。
i可以理解为背包重量,wordDict中的元素为物品。
transfer: dp[i]=True的情况为存在物品word,使s[i-len(word):i]==word,
并且dp[i-len(word)]==True即拿物品word之前的字符串也能拼接出来,
同时满足以上两种情况极为True。
result: 返回dp[-1]即为字符串s能否拼接出来。
'''
n = len(s)
dp = [True] + [False] * n
for i in range(1, n+1):
for word in wordDict:
if i >= len(word):
dp[i] = (dp[i-len(word)] and s[i-len(word):i] == word)
if dp[i] == True:
break
return dp[-1]
c++
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
// state: dp[i]表示s[0-i]的子字符串可以被拼接出来
// basecase: dp[0]=true
// transfer: 遍历所有word,提取i往前word长度n的子字符串sub,dp[i]=true条件为sub==word并且dp[i-n]==true
// result: dp[s]
int n = s.size();
vector<bool> dp(n+1, false);
dp[0] = true;
int word_len;
string sub_s;
for (int i = 1; i <= n; i++) {
for (auto& word : wordDict) {
word_len = word.size();
if (i < word_len) continue;
sub_s = s.substr(i-word_len, word_len);
if (sub_s == word && dp[i-word_len]) dp[i] = true;
if (dp[i]) break;
}
}
return dp[n];
}
};