Distinct Subsequences

来源:互联网 发布:北京北大青鸟网络学校 编辑:程序博客网 时间:2024/06/05 01:55

题目

Given a string S and a string T, count the number of distinct subsequences of T in S.

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(i)表示第i个字符之前的S的子串(不包含第i个字符),同理设T(j)表示第j个字符之前的T的子串。

设C(i,j)表示S(i)中有T(j)的个数

于是就有递推关系:

if (当第S(i)的最后一个字符与T(j)的最后一个字符相等时)  C(i,j)=C(i-1,j)+C(i-1,j-1);

else C(i,j)=C(i-1,j) 

上面对于if语句成立时,S(i)字符串可以分为俩类

一是S(i)包含结果中一定含有最后一个字符的情况:共有C(i-1,j-1)

二是S(i)包含C(j)中不包含最后一个字符的情况:C(i-1,j)

在编写程序时自然可以利用一个二维数组table[i][j]来表示C(i,j)的值。

java code:

public class DistinctSubsequences {public static int numDistincts(String S, String T) {int[][] table = new int[S.length() + 1][T.length() + 1];for (int i = 0; i <= S.length(); i++) {table[i][0] = 1;// 初始化S到T的空子串为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)) {table[i][j] = table[i - 1][j - 1] + table[i - 1][j];} else {table[i][j] = table[i - 1][j];}}}return table[S.length()][T.length()];}public static void main(String[] args) {// String S = "b", T = "b";// String S = "abc", T = "";String S = "rabbbit", T = "rabbit";System.out.println(numDistincts(S, T));}}


0 0