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思想 :1. S(i) -> T(j) = S(i-1)->T(j) if s.charAt(i) != t.charAt(j)
2. S(i) -> T(j) = S(i-1) -> T(j-1) + S(i-1)->T(j) if s.charAt(i) == t.charAt(j)
public int numDistinct(String S, String T) {
int row = S.length();
int col = T.length();
int[][] num = new int[row+1][col+1];
for(int i = 0; i <= row; i++){
for(int j = 0; j <= col; j++){
if(i==0){
if(j == 0) num[i][j] = 1;
else num[i][j] = 0;
}else if(j == 0){
num[i][j] = 1;
}else{
num[i][j] = num[i-1][j];
if(S.charAt(i-1) == T.charAt(j-1)){
num[i][j] +=num[i-1][j-1];
}
}
}
}
return num[row][col];
}
No comments:
Post a Comment