Distinct Subsequences

本文介绍了一种使用动态规划解决子序列计数问题的方法。通过构建二维数组记录中间状态,实现了高效计算一个字符串中与另一个字符串相等的子序列数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值