题目:
Given a string S and a string 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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
题意及分析:给定字符串S和T,若S中删除某些字符之后能得到T,求有几种方式。使用动态规划的方式求解,使用一个数组men[s.length+1][t.length+1]来保存S从开始位置到i和T从开始位置到j能够匹配的个数,即S(0,i)中包含多少个T(0,j)的子序列。
这里分三种情况:
1、i==0,即s为空,那么men[0][j]=0
2、j==0,即t为空,那么men[i][0]=1
3、对于i>0&&j>0有:
(1)若s.charAt(i-1) !=t.chatAt(j-1),那么s的i点加入不加入影响都是一样的,即men[i][j] = men[i-1][j]
(2)若s.charAt(i-1) ==t.chatAt(j-1),那么当前字符可选择匹配或者是不匹配,所以men[i][j] = men[i - 1][j -1] + men[i - 1][j];
代码:
class Solution { public int numDistinct(String s, String t) { int[][] men = new int[s.length()+1][t.length()+1]; //men[i][j]代表s从开始位置到i,t从开始位置到j 子串匹配的个数,可以得到men[i][j]>=men[i-1][j] //当i为0,即s子串为空的时候,men[i][j]==0 for(int j=0;j<t.length();j++){ men[0][j] =0; } //当j=0,即t子串为空,men[i][j]=1 for (int i=0;i<s.length();i++){ men[i][0] = 1; } for(int i=1;i<=s.length();i++){ for(int j=1;j<=t.length();j++){ men[i][j] = men[i-1][j]; if(s.charAt(i-1)==t.charAt(j-1)){ men[i][j] += men[i-1][j-1]; } } } return men[s.length()][t.length()]; } }