mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
add: 0392.判断子序列 typescript 新增滚动数组解法
This commit is contained in:
@ -216,6 +216,8 @@ const isSubsequence = (s, t) => {
|
||||
|
||||
### TypeScript:
|
||||
|
||||
> 二维数组
|
||||
|
||||
```typescript
|
||||
function isSubsequence(s: string, t: string): boolean {
|
||||
/**
|
||||
@ -236,6 +238,31 @@ function isSubsequence(s: string, t: string): boolean {
|
||||
}
|
||||
```
|
||||
|
||||
> 滚动数组
|
||||
```typescript
|
||||
function isSubsequence(s: string, t: string): boolean {
|
||||
const sLen = s.length
|
||||
const tLen = t.length
|
||||
const dp: number[] = new Array(tLen + 1).fill(0)
|
||||
|
||||
for (let i = 1; i <= sLen; i++) {
|
||||
let prev: number = 0;
|
||||
let temp: number = 0;
|
||||
for (let j = 1; j <= tLen; j++) {
|
||||
// 备份一下当前状态(经过上层迭代后的)
|
||||
temp = dp[j]
|
||||
// prev 相当于 dp[j-1](累加了上层的状态)
|
||||
// 如果单纯 dp[j-1] 则不会包含上层状态
|
||||
if (s[i - 1] === t[j - 1]) dp[j] = prev + 1
|
||||
else dp[j] = dp[j - 1]
|
||||
// 继续使用上一层状态更新参数用于当前层下一个状态
|
||||
prev = temp
|
||||
}
|
||||
}
|
||||
return dp[tLen] === sLen
|
||||
}
|
||||
```
|
||||
|
||||
### Go:
|
||||
|
||||
二维DP:
|
||||
|
Reference in New Issue
Block a user