添加Go的另外一种解法

可以将题目转化为“求装满背包s的前几位字符的方式有几种”, 然后判断最后dp[len(s)]是否大于0就可。
This commit is contained in:
KiloG
2022-10-07 21:26:39 +08:00
committed by GitHub
parent 27381c9729
commit 3223112124

View File

@ -344,6 +344,21 @@ func wordBreak(s string,wordDict []string) bool {
}
return dp[len(s)]
}
// 转化为 求装满背包s的前几位字符的方式有几种
func wordBreak(s string, wordDict []string) bool {
// 装满背包s的前几位字符的方式有几种
dp := make([]int, len(s)+1)
dp[0] = 1
for i := 0; i <= len(s); i++ { // 背包
for j := 0; j < len(wordDict); j++ { // 物品
if i >= len(wordDict[j]) && wordDict[j] == s[i-len(wordDict[j]):i] {
dp[i] += dp[i-len(wordDict[j])]
}
}
}
return dp[len(s)] > 0
}
```
Javascript