leetcode@ [72/115] Edit Distance & Distinct Subsequences (Dynamic Programming)

时间:2023-03-09 18:43:16
leetcode@ [72/115] Edit Distance & Distinct Subsequences (Dynamic Programming)

https://leetcode.com/problems/edit-distance/

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

用dp[i][j] 来表示 长度为 i 的 word1 经过 dp[i][j]次变换 可以得到长度为 j 的word2,那么我们主要考察两种情况,第一种是:word1[i] == word2[j],那么这个问题的规模便转换成了:dp[i][j] = dp[i-1][j-1]. 第二种情况是:word1[i] != word2[j],那么我们可以删除掉word1中的第 i 个字符,或者我们可以把 word1中的第 i 个字符换成与 word2[j] 相同的字符,或者我们还可以同时 删除 word1[i] 和 word2[j]. 于是状态转移方程为:dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1.

class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length(); vector<vector<int> > dp(m+, vector<int> (n+, )); for(int i=;i<=m;++i) dp[i][] = i;
for(int j=;j<=n;++j) dp[][j] = j; for(int i=;i<=m;++i) {
for(int j=;j<=n;++j) {
if(word1[i-] == word2[j-]) {
dp[i][j] = min(dp[i-][j-], dp[i-][j]+);
}
else {
dp[i][j] = min(dp[i-][j], min(dp[i][j-], dp[i-][j-])) + ;
}
}
} return dp[m][n];
}
};

https://leetcode.com/problems/distinct-subsequences/

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit", T = "rabbit"

Return 3.

解题报告:用 dp[i][[j] 来表示长度为 i 的 S串 包含了几个 T串。分两种情况考虑,第一种:S[i] != T[j],那么问题转而变成求S[1,...i-1] 包含了几个 T[1...i]。因为S[i] 对解的个数不会产生影响。第二种: S[i] == T[j],那么一种可能是 S[1...i-1] 包含了 若干个 T[1...j-1],或者是S[1...i-1] 包含了 若干个T[1...j]。所以状态转移方程为:

dp[i][j] = dp[i-1][j] + dp[i-1][j-1] (if S[i] == T[j])

dp[i][j] = dp[i-1][j] (if S[i] != T[j])

class Solution {
public:
int numDistinct(string s, string t) {
int m = s.length(), n = t.length();
vector<vector<int> > dp(m+, vector<int>(n+, )); for(int i=;i<=m;++i) dp[i][] = ; for(int i=;i<=m;++i) {
for(int j=;j<=n;++j) {
if(s[i-] == t[j-]) dp[i][j] = dp[i-][j-] + dp[i-][j];
else dp[i][j] = dp[i-][j];
}
} return dp[m][n];
}
};