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.
 * 
 * f(i, j) = f(i - 1, j) + S[i] == T[j]? f(i - 1, j - 1) : 0 Where f(i, j) is
 * the number of distinct sub-sequence for T[0:j] in S[0:i].
 */

就是给你两个字符串S,T,来判断T字符串中的字符序列在S字符序列中出现的次数(注意这道题是序列,不是子串,也就是只要字符按照顺序出现即可,不需要连续出现)。这是一道经典的DP问题。现在我们维护一个二维数组f[i][j]来表示T[0…j]在S[0…i] 有多少种可行的序列。下面来看一下推算的过程:
如果S的第i个字符和T的第j个字符不相同,那么就是说f[ i-1 ][j]和f[i][j]是一样的,前面是多少还是多少。S的第i个字符加入也不会多一种结果。
如果S的第i个字符和T的第j 个字符相同,那么f[i-1][j-1]中所有满足结果的序列会成为新的满足的序列。当然f[i-1][j]也是可行的结果。所以地推的代码如下:

if (S.charAt(i - 1) == T.charAt(j - 1)) {
                    f[i][j] += f[i - 1][j] + f[i - 1][j - 1];
                } else {
                    f[i][j] += f[i - 1][j];
                }

具体代码如下:

public static int numDistinct(String S, String T) {
        int[][] f = new int[S.length() + 1][T.length() + 1];
        for (int k = 0; k < S.length(); k++)
            f[k][0] = 1;
        for (int i = 1; i <= S.length(); i++) {
            for (int j = 1; j <= T.length(); j++) {
                if (S.charAt(i - 1) == T.charAt(j - 1)) {
                    f[i][j] += f[i - 1][j] + f[i - 1][j - 1];
                } else {
                    f[i][j] += f[i - 1][j];
                }
            }
        }
        return f[S.length()][T.length()];
    }

f[i][0]初始化为1的含义是:任何长度的S,如果转换为空串,那就只有删除全部字符这1种方式。

参考博客:http://www.tuicool.com/articles/6BZRJf
http://www.cnblogs.com/ganganloveu/p/3836519.html

猜你喜欢

转载自blog.csdn.net/u011521382/article/details/52023037
今日推荐