LeetCode:Distinct Subsequences

Distinct Subsequences




Total Accepted: 51556  Total Submissions: 177996  Difficulty: Hard

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

Hide Tags
  Dynamic Programming String




















题意:求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];
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值