本文主要是介绍算法训练营day59,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目1:115. 不同的子序列 - 力扣(LeetCode)
这里的初始化第一列为1,表示t是空字符串 在s的子序列中有1种情况
递推公式也不同
class Solution {
public:int numDistinct(string s, string t) {vector<vector<int>> dp(s.size() + 1, vector<int>(t.size() + 1));for(int i = 0;i <= s.size();i++) {dp[i][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] + dp[i - 1][j];}elsedp[i][j] = dp[i - 1][j];}}return dp[s.size()][t.size()];}
};
题目2:583. 两个字符串的删除操作 - 力扣(LeetCode)
class Solution {
public:int minDistance(string word1, string word2) {vector<vector<int>> dp(word1.size() + 1, vector<int>(word2.size() + 1));for(int i = 1;i <= word1.size();i++) {dp[i][0] = i;}for(int j = 1;j <= word2.size();j++) {dp[0][j] = j;}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()];}
};
题目3:72. 编辑距离 - 力扣(LeetCode)
class Solution {
public:int minDistance(string word1, string word2) {vector<vector<int>> dp(word1.size() + 1, vector<int>(word2.size() + 1));for(int i = 1;i <= word1.size();i++) dp[i][0] = i;for(int j = 1;j <= word2.size();j++) dp[0][j] = j;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()];}
};
这篇关于算法训练营day59的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!