标签:leetcode java distinct subsequence
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 ,统计T作为S的子序列共有多少种。
这里定义的字符串的一个子序列是指,在原字符串中在保持原相对字母顺序的前提下,删除一些(可以为0 )字符。(例如,"ACE" 是"ABCDE"的子序列,而"AEC"不是)
这里给出一个例子:
S = "rabbbit"
, T = "rabbit"
Return 3
.
DP 动态规划
首先设置动态规划数组dp[i][j],表示S串中从开始位置到第i位置与T串从开始位置到底j位置匹配的子序列的个数。
如果S串为空,那么dp[0][j]都是0;
如果T串为空,那么dp[i][j]都是1,因为空串为是任何字符串的字串。
如果S的第i个字符与T的第j个字符不同,则res[i][j]的序列个数应该与res[i-1][j]的个数相同;
如果S的第i个字符与T的第j个字符相同,那么除了要考虑res[i-1][j-1]的个数情况,还要考虑res[i-1][j]的个数;
因此,递推式定义如下:
if(S.charAt(i)==T.charAt(j))
res[i][j]=res[i-1][j-1]+res[i-1][j];
else res[i][j]=res[i-1][j];
public class Solution { public int numDistinct(String S, String T) { //采用动态规划的思想,定义维护量res[i][j]:表示S的前i个元素和T的前j个元素能够匹配的转化方式 int[][] res = new int[S.length() + 1][T.length() + 1]; res[0][0] = 1;//initial //进行初始化 for(int j = 1; j <= T.length(); j++)//S is empty res[0][j] = 0; for (int i = 1; i <= S.length(); i++)//T is empty res[i][0] = 1; for(int i=1;i<S.length()+1;i++) { for(int j=1;j<T.length()+1;j++) { if(S.charAt(i-1)==T.charAt(j-1)) res[i][j]=res[i-1][j-1]+res[i-1][j]; else res[i][j]=res[i-1][j]; } } return res[S.length()][T.length()]; } }
版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java] Distinct Subsequences
标签:leetcode java distinct subsequence
原文地址:http://blog.csdn.net/evan123mg/article/details/47036945