码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Distinct Subsequences

时间:2016-05-30 14:59:05      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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





















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

标签:

原文地址:http://blog.csdn.net/itismelzp/article/details/51531210

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!