From aaa8cc2443a9a05e5af3acae67d7f593c7c34077 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Sun, 23 Jul 2023 19:40:19 +0800 Subject: [PATCH] =?UTF-8?q?Update=200115.=E4=B8=8D=E5=90=8C=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0115.不同的子序列.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0115.不同的子序列.md b/problems/0115.不同的子序列.md index 56516132..91f35291 100644 --- a/problems/0115.不同的子序列.md +++ b/problems/0115.不同的子序列.md @@ -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]; + // 当开始遍历 t,s 的前 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()] + } +} +```