From 3223112124c71c21fef1354a451b12a64c118f7d Mon Sep 17 00:00:00 2001 From: KiloG <33695125+JOJO0527@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:26:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Go=E7=9A=84=E5=8F=A6=E5=A4=96?= =?UTF-8?q?=E4=B8=80=E7=A7=8D=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可以将题目转化为“求装满背包s的前几位字符的方式有几种”, 然后判断最后dp[len(s)]是否大于0就可。 --- problems/0139.单词拆分.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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: