115.不同的子序列
class Solution {
public:
int numDistinct(string s, string t) {
int mod=1e9+7;
vector<vector<int>> dp(s.size() + 1, vector<int>(t.size() + 1, 0));
for (int i = 0; i <= s.size(); i++)
dp[i][0] = 1;
for (int i = 0; i <= t.size(); i++)
dp[0][i] = 0;
dp[0][0] = 1;
for (int i = 1; i <= s.size(); i++) {
for (int j = 1; j <= t.size(); j++) {
if (s[i - 1] == t[j - 1])
dp[i][j] = dp[i - 1][j - 1]% mod + dp[i - 1][j]% mod;
else
dp[i][j] = dp[i - 1][j]% mod;
}
}
return dp[s.size()][t.size()];
}
};
`这道题dp[i][j]的含义为以i-1,j-1结尾的s,t字符串中,s中有多少种t的组合,递推公式为当s[i-1]==t[j-1]时,dp[i][j]=dp[i-1][j-1]+dp[i-1][j],else dp[i][j]=dp[i-1][j],因为是s中以i-1为下标有多少种t中以t-1为下标结尾的字符串组合,所以都是在s中找t,所以t的下标不变,在i-2里面找,所以才有dp[i-1][j],注意结果要对dp数组取模,int mod=1e9+7
583. 两个字符串的删除操作
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size()+1,vector<int>(word2.size()+1,0));
for(int i=1;i<=word1.size();i++){
for(int j=1;j<=word2.size();j++){
if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
return word1.size()+word2.size()-2*dp[word1.size()][word2.size()];
}
};
这道题可以用之前求最长公共子序列的思路来做,求出最长的公共子序列,然后用两字符串的长度和减去公共长度,最后得到的就是最小步数
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size()+1,vector<int>(word2.size()+1,0));
for(int i=0;i<=word1.size();i++) dp[i][0]=i;
for(int j=0;j<=word2.size();j++) dp[0][j]=j;
dp[0][0]=0;
for(int i=1;i<=word1.size();i++){
for(int j=1;j<=word2.size();j++){
if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1);
}
}
return dp[word1.size()][word2.size()];
}
};
这道题用删减的思路来做就是这种写法,dp[i][j]的含义就是以i-1为结尾,j-1为结尾的word1,word2字符串,要相等要减去的最少步数,所以递推公式为if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1],因为相等了所以不需要删减元素,else dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1),否则就删掉word1[i-1],所以dp[i][j]=dp[i-1][j]+1,同理删掉word2[j-1]
72. 编辑距离
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size()+1,vector<int>(word2.size()+1,0));
for(int i=0;i<=word1.size();i++) dp[i][0]=i;
for(int i=0;i<=word2.size();i++) dp[0][i]=i;
for(int i=1;i<=word1.size();i++){
for(int j=1;j<=word2.size();j++){
if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+1));
}
}
return dp[word1.size()][word2.size()];
}
};
这道题编辑距离。dp[i][j]的含义为以i-1,j-1为结尾的word1,word2字符串,增删改为同一字符串的最小步数,所以dp[i][j]的递推公式为dp[i][j]=dp[i-1][j-1],else dp[i][j]=min({dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1}),这三项分别对应了删,增,改,其中word2删,就是对应着word1增