[Leetcode] Distinct Subsequences
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中的个数。
一个字符串的子序列是一个新的字符串,其从源字符串头部开始,中间可能删除一些字符,不改变现有字符的相对顺序。(例如,"ACE"
是"ABCDE"
的子序列,但 "AEC"
不是)
这是一个例子:
S = "rabbbit"
, T = "rabbit"
返回 3
.
Solution: dp
- -自己做的时候也想到了用一张二维表来做,但是肿么初始化dp[i][0]和dp[0][i]那里就confused掉了。。。。。
大神的解答:
http://blog.csdn.net/worldwindjp/article/details/19770281
1. If both T and S are empty, the number of distinct subsequence (NDS) is 1. (they match each other)
2. If the T is empty, S is not empty, then the number of distinct subsequences is still 1.
3. 如果S[j]==T[i],那么dp[i][j] = dp[i-1][j-1] + dp[i][j-1]。意思是:如果当前S[j]==T[i],那么当前这个字母即可以保留也可以抛弃,所以变换方法等于保留这个字母的变换方法加上不用这个字母的变换方法。
如果S[i]!=T[i],那么dp[i][j] = dp[i-1][j],意思是如果当前字符不等,那么就只能抛弃当前这个字符。
递归公式中用到的dp[0][0] = 1,dp[i][0] = 0(把任意一个字符串变换为一个空串只有一个方法)
1 public class Solution { 2 public int numDistinct(String S, String T) { 3 int[][] dp = new int[T.length() + 1][S.length() + 1]; 4 for (int i = 0; i <= S.length(); ++i) { 5 dp[0][i] = 1; 6 } 7 for (int i = 1; i <= T.length(); ++i) { 8 dp[i][0] = 0; 9 } 10 for (int i = 1; i <= T.length(); ++i) { 11 for (int j = 1; j <= S.length(); ++j) { 12 dp[i][j]=(S.charAt(j-1)==T.charAt(i-1))?dp[i-1][j-1]+dp[i][j-1]:dp[i][j-1]; 13 } 14 } 15 return dp[T.length()][S.length()]; 16 } 17 }