[刷题]Distinct Subsequences

来源:互联网 发布:unix网络编程源码下载 编辑:程序博客网 时间:2024/05/17 00:01

[LintCode]Distinct Subsequences

public class Solution {    /**     * @param S, T: Two string.     * @return: Count the number of distinct subsequences     */    public int numDistinct(String S, String T) {        // 2015-05-24 不是很理解        if (S == null || T == null) {            return 0;        }        int sLen = S.length();        int tLen = T.length();        int dp[][] = new int[tLen + 1][sLen + 1];        for (int j = 0; j <= sLen; j++) {            dp[0][j] = 1;        }        for (int i = 1; i <= tLen; i++) {            dp[i][0] = 0;        }        for (int i = 1; i <= tLen; i++) {            for (int j = 1; j <= sLen; j++) {                if (i > j) {                    dp[i][j] = 0;                    continue;                }                dp[i][j] = dp[i][j - 1];                if (T.charAt(i - 1) == S.charAt(j - 1)) {                    dp[i][j] += dp[i - 1][j - 1];                }            }        }        return dp[tLen][sLen];            }}
note:

1、对于dp[i][j],一定有dp[i][j] = dp[i][j - 1]。

2、如果T.charAt(i - 1) == S.charAt(j - 1),则dp[i][j] += dp[i - 1][j - 1]

0 0
原创粉丝点击