●115.不同的子序列
class Solution {
public int numDistinct(String s, String t) {
int[][] dp = new int[s.length()+1][t.length()+1];
for(int i = 0;i<s.length()+1;i++){
dp[i][0]=1;
}
for(int i = 1;i<=s.length();i++){
for(int j =1 ;j<=t.length();j++){
if(s.charAt(i-1)==t.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+dp[i-1][j];
}else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[s.length()][t.length()];
}
}
●583. 两个字符串的删除
太难了,真的不懂
class Solution {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length()+1][word2.length()+1];
for(int i = 0;i<word1.length()+1;i++){
dp[i][0] = i;
}
for(int i = 0;i<word2.length()+1;i++){
dp[0][i] = i;
}
//dp[0][0]=0;
for(int i = 1;i<word1.length()+1;i++){
for(int j = 1;j<word2.length()+1;j++){
if(word1.charAt(i-1)==word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
//dp[i][j] = Math.min(dp[i-1][j]+1,Math.max(dp[i][j-1]+1,dp[i-1][j-1]));
dp[i][j] = Math.min(dp[i-1][j]+1,dp[i][j-1]+1);
}
}
}
return dp[word1.length()][word2.length()];
}
}
●72. 编辑距离
好像有点明白了。
需要特别关注的是
word1的增和删的操作次数与word2的删除和增加的操作次数是分别对应的,是相等的。
class Solution {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length()+1][word2.length()+1];
for(int i = 0;i<word1.length()+1;i++){
dp[i][0]=i;
}
for(int j = 0;j<word2.length()+1;j++){
dp[0][j]=j;
}
for(int i = 1;i<word1.length()+1;i++){
for(int j = 1;j<word2.length()+1;j++){
if(word1.charAt(i-1)==word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = Math.min(dp[i-1][j]+1,Math.min(dp[i][j-1]+1,dp[i-1][j-1]+1));
}
}
}
return dp[word1.length()][word2.length()];
}
}