标签:
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
.
首先分析问题,能不能转化为更小的子问题,比如T = ACE, S = ABCACED,最直接的办法就是回溯法,看T是否是S的子序列,可以算是标准的回溯法了,明显这个是有重复子结构的。所以问题就可以转化为动态规划,dp问题的关键在于状态转移方程:
dp[i][]j] = dp[i][j-1] t[i] != s[j];
dp[i][]j] = dp[i][j-1] + dp[i-1][j-1]; t[i] == s[j];
先罗列出来上面的公式,其实分析这个问题还是比较简单的,我们只需要盯住最后一个字符就可以了,即t[i],s[j]。接下来就可以分析字符串的操作了,题中已经给出A subsequence of a string is a new string which is formed from the original string by deleting some,所以对于字符s[j]需要进行一种操作,就是delete or not,如果删除的话,还要考虑最后两个字符的关系。
首先,如果delete的话,显然是递推式dp[i][]j] = dp[i][j-1]
其次,如果不delete的话,需要考虑最后一个字符
如果不相等,最后一个字符计算不删除我们也是用不上的,所以还是dp[i][]j] = dp[i][j-1]
如果相等的话,我们可以让最后两个字符匹配,于是问题就简化为子问题了dp[i-1][j-]。所以递推式必须在加上一项了,即dp[i][]j] = dp[i][j-1] + dp[i-1][j-1];
分析过程很重要,之后的码代码就比较容易了,不同人有不同的版本,如下是我自己的版本,一次AC
public int numDistinct(String s, String t) { if (t == null) return 1; else if (s == null) return 0; int[][] dp = new int[t.length()+1][s.length()+1]; for (int i = 0; i < dp[0].length; i++) { dp[0][i] = 1; } for (int i = 1; i < dp.length; i++) { for (int j = i; j < dp[i].length; j++) { dp[i][j] = dp[i][j-1]; if (t.charAt(i-1) == s.charAt(j-1)) { dp[i][j] += dp[i-1][j-1]; } } } return dp[t.length()][s.length()]; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode-Distinct Subsequences
标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/48052501