118 · 不同的子序列Distinct Subsequences
描述
Given two strings S and T. Count the number of distinct subsequences of S which equals T.
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)
Input:
S = “rabbbit”
T = “rabbit”
Output:
3
Explanation:
You could remove any ‘b’ in S, so there are 3 ways to get T.
public class Solution {
/**
* @param S: A string
* @param T: A string
* @return: Count the number of distinct subsequences
*/
public int numDistinct(String S, String T) {
// write your code here
int n = S.length() , m = T.length() ;
int[][] dp = new int[m+1][n+1] ;
for(int i = 0 ; i <= n ; i++){
dp[0][i] = 1 ;
}
for(int i = 1 ; i <= m ; i++){
for(int j = 1 ; j <= n ; j++){
if(T.charAt(i-1)==S.charAt(j-1))
dp[i][j] = dp[i-1][j-1] +dp[i][j-1];
else
dp[i][j] = dp[i][j-1];
}
}
return dp[dp.length-1][dp[0].length-1];
}
}