Skip to content

Commit 3223112

Browse files
authored
添加Go的另外一种解法
可以将题目转化为“求装满背包s的前几位字符的方式有几种”, 然后判断最后dp[len(s)]是否大于0就可。
1 parent 27381c9 commit 3223112

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

problems/0139.单词拆分.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,21 @@ func wordBreak(s string,wordDict []string) bool {
344344
}
345345
return dp[len(s)]
346346
}
347+
// 转化为 求装满背包s的前几位字符的方式有几种
348+
func wordBreak(s string, wordDict []string) bool {
349+
// 装满背包s的前几位字符的方式有几种
350+
dp := make([]int, len(s)+1)
351+
dp[0] = 1
352+
for i := 0; i <= len(s); i++ { // 背包
353+
for j := 0; j < len(wordDict); j++ { // 物品
354+
if i >= len(wordDict[j]) && wordDict[j] == s[i-len(wordDict[j]):i] {
355+
dp[i] += dp[i-len(wordDict[j])]
356+
}
357+
}
358+
}
359+
360+
return dp[len(s)] > 0
361+
}
347362
```
348363

349364
Javascript:

0 commit comments

Comments
 (0)