mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加(0139.单词拆分.md):增加typescript版本
This commit is contained in:
@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user