LeetCode:Distinct Subsequences
Posted walker lee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Distinct Subsequences相关的知识,希望对你有一定的参考价值。
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
.
Subscribe to see which companies asked this question
题意:求S到T的的可能变换。
思路:动规
设:S = "rabbbit",T="rabbit"
dp[T.length()+1][S.length()+1];
手动计算可得:
j 0 1 2 3 4 5 6 7
i S r a b b b i t
0 T 1 1 1 1 1 1 1 1
1 r 0 1 1 1 1 1 1 1
2 a 0 0 1 1 1 1 1 1
3 b 0 0 0 1 2 3 3 3
4 b 0 0 0 0 1 3 3 3
5 i 0 0 0 0 0 0 3 3
6 t 0 0 0 0 0 0 0 3
结果即为:3(==dp[T.length()][S.length()] );
观察上面dp表中的划横线部分数字,生成过程可以得到:
if(T[i] == S[j]) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
else dp[i][j] = dp[i][j-1];
即:
当T[i] == S[j],当前字符可以保留也可以舍弃;
当T[i] != S[j]时,当前字符只能舍弃。
i==0时,表示T为空,这时只有一种变换可能,即去掉S中全部字符。
java code:
public class Solution { public int numDistinct(String s, String t) { int m = t.length(); int n = s.length(); int[][] dp = new int[m+1][n+1]; for(int i=0;i<=m;i++) dp[i][0] = 0; for(int j=0;j<=n;j++) dp[0][j] = 1; for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++) { if(s.charAt(j-1)==t.charAt(i-1)) dp[i][j] = dp[i-1][j-1] + dp[i][j-1]; else dp[i][j] = dp[i][j-1]; } } return dp[m][n]; } }
以上是关于LeetCode:Distinct Subsequences的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]Distinct Subsequences,解题报告
[LeetCode]Distinct Subsequences,解题报告
LeetCode:Distinct Subsequences
[LeetCode] Distinct Subsequences [29]