From 2fb34b30b38ee73624d65d183955cef3a80caced Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 8 May 2022 18:28:32 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880139.=E5=8D=95?= =?UTF-8?q?=E8=AF=8D=E6=8B=86=E5=88=86.md=EF=BC=89:=E5=A2=9E=E5=8A=A0types?= =?UTF-8?q?cript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0139.单词拆分.md | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index ac834f04..5b4e92b9 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -345,6 +345,48 @@ const wordBreak = (s, wordDict) => { } ``` +TypeScript: + +> 动态规划 + +```typescript +function wordBreak(s: string, wordDict: string[]): boolean { + const dp: boolean[] = new Array(s.length + 1).fill(false); + dp[0] = true; + for (let i = 1; i <= s.length; i++) { + for (let j = 0; j < i; j++) { + const tempStr: string = s.slice(j, i); + if (wordDict.includes(tempStr) && dp[j] === true) { + dp[i] = true; + break; + } + } + } + return dp[s.length]; +}; +``` + +> 记忆化回溯 + +```typescript +function wordBreak(s: string, wordDict: string[]): boolean { + // 只需要记忆结果为false的情况 + const memory: boolean[] = []; + return backTracking(s, wordDict, 0, memory); + function backTracking(s: string, wordDict: string[], startIndex: number, memory: boolean[]): boolean { + if (startIndex >= s.length) return true; + if (memory[startIndex] === false) return false; + for (let i = startIndex + 1, length = s.length; i <= length; i++) { + const str: string = s.slice(startIndex, i); + if (wordDict.includes(str) && backTracking(s, wordDict, i, memory)) + return true; + } + memory[startIndex] = false; + return false; + } +}; +``` + -----------------------