Distinct Subsequences
Given two strings S and T. count the number of distinct subsequences of S that equals T.
e.g. S = "rabbbit", T = "rabit" return 3
Solution:
1. Denote that dp[i][j] is the number of distinct subsequences of S[0..i-1] that equals T[0..j-1].
2. Recursive Relation:
if S[i-1] == T[j-1] dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
e.g. S = abcc, T = abc. We can consider "abc" and "ab" plus the following 'c'. Or we can simply consider "abc" and "abc" without the following 'c'
if S[i-1] != T[j-1] dp[i][j] = dp[i-1][j]
e.g. S = abcdc, T = abd. We just consider "abcd" and "abd".
Therefore,
dp[i][j] = dp[i-1][j] + S[i-1] == T[j-1]? dp[i-1][j-1] : 0;
3.Initialization:
dp[i][0] = 1. As every String can contain a subsequence of an empty string.
Code:
public class Solution { public int numDistinct(String s, String t) { if(s.length()<t.length()) return 0; if(s.length()==t.length() && s.equals(t)) return 1; int[][] dp = new int[s.length()+1][t.length()+1]; for(int i = 0; i <=s.length(); i++) dp[i][0]=1; for(int i = 0; i < s.length(); i++){ for(int j = 0; j < t.length(); j++){ if(s.charAt(i)==t.charAt(j)){ dp[i+1][j+1]=dp[i][j]+dp[i][j+1]; }else{ dp[i+1][j+1]=dp[i][j+1]; } } } return dp[s.length()][t.length()]; } }

浙公网安备 33010602011771号