diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index d60fd46c..5226502a 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -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: