美文网首页
Distinct Subsequences

Distinct Subsequences

作者: BLUE_fdf9 | 来源:发表于2018-10-05 01:58 被阅读0次

题目
Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation:

As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^

答案

class Solution {
    public int numDistinct(String ss, String tt) {
        char[] s = ss.toCharArray(), t = tt.toCharArray();
        int m = s.length, n = t.length;
        
        /*
            Define f[i][j]: number of occurences of t[0...j-1] in s[0...i-1]
            f[i][j] = (f[i - 1][j - 1], if s[i - 1] == t[j - 1]) + (f[i - 1][j])
        */
        int[][] f = new int[m + 1][n + 1];
        for(int i = 0; i <= m; i++) {
            for(int j = 0; j <= n; j++) {
                if(j == 0) {
                    f[i][j] = 1;
                    continue;
                }

                if(i == 0) {
                    f[i][j] = 0;
                    continue;
                }
                
                f[i][j] = f[i - 1][j];
                if(s[i - 1] == t[j - 1])
                    f[i][j] += f[i - 1][j - 1];
            }
        }
        return f[m][n];
    }
}

相关文章

网友评论

      本文标题:Distinct Subsequences

      本文链接:https://www.haomeiwen.com/subject/fqvfaftx.html