Update 0115.不同的子序列.md

This commit is contained in:
fwqaaq
2023-07-23 19:40:19 +08:00
committed by GitHub
parent f0ac0b2efd
commit aaa8cc2443

View File

@ -337,6 +337,36 @@ impl Solution {
}
```
> 滚动数组
```rust
impl Solution {
pub fn num_distinct(s: String, t: String) -> i32 {
if s.len() < t.len() {
return 0;
}
let (s, t) = (s.into_bytes(), t.into_bytes());
// 对于 t 为空字符串s 作为子序列的个数为 1删除 s 所有元素)
let mut dp = vec![1; s.len() + 1];
for char_t in t {
// dp[i - 1][j - 1]dp[j + 1] 更新之前的值
let mut pre = dp[0];
// 当开始遍历 ts 的前 0 个字符无法包含任意子序列
dp[0] = 0;
for (j, &char_s) in s.iter().enumerate() {
let temp = dp[j + 1];
if char_t == char_s {
dp[j + 1] = pre + dp[j];
} else {
dp[j + 1] = dp[j];
}
pre = temp;
}
}
dp[s.len()]
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">