Skip to content

Commit 91399c3

Browse files
Merge pull request youngyangyang04#1295 from xiaofei-2020/dp26
添加(0139.单词拆分.md):增加typescript版本
2 parents 3814018 + 2fb34b3 commit 91399c3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

problems/0139.单词拆分.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,48 @@ const wordBreak = (s, wordDict) => {
345345
}
346346
```
347347

348+
TypeScript:
349+
350+
> 动态规划
351+
352+
```typescript
353+
function wordBreak(s: string, wordDict: string[]): boolean {
354+
const dp: boolean[] = new Array(s.length + 1).fill(false);
355+
dp[0] = true;
356+
for (let i = 1; i <= s.length; i++) {
357+
for (let j = 0; j < i; j++) {
358+
const tempStr: string = s.slice(j, i);
359+
if (wordDict.includes(tempStr) && dp[j] === true) {
360+
dp[i] = true;
361+
break;
362+
}
363+
}
364+
}
365+
return dp[s.length];
366+
};
367+
```
368+
369+
> 记忆化回溯
370+
371+
```typescript
372+
function wordBreak(s: string, wordDict: string[]): boolean {
373+
// 只需要记忆结果为false的情况
374+
const memory: boolean[] = [];
375+
return backTracking(s, wordDict, 0, memory);
376+
function backTracking(s: string, wordDict: string[], startIndex: number, memory: boolean[]): boolean {
377+
if (startIndex >= s.length) return true;
378+
if (memory[startIndex] === false) return false;
379+
for (let i = startIndex + 1, length = s.length; i <= length; i++) {
380+
const str: string = s.slice(startIndex, i);
381+
if (wordDict.includes(str) && backTracking(s, wordDict, i, memory))
382+
return true;
383+
}
384+
memory[startIndex] = false;
385+
return false;
386+
}
387+
};
388+
```
389+
348390

349391

350392
-----------------------

0 commit comments

Comments
 (0)