LeetCode115(2021.3.17)

LC115. 不同的子序列

class Solution {
    public int numDistinct(String s, String t) {
        int ls = s.length(), lt = t.length();
        if (ls < lt) {
            return 0;
        }
        int[][] dp = new int[ls + 1][lt + 1];
        for (int i = 0; i <= ls; ++i) {
            dp[i][lt] = 1;
        }
        for (int i = ls - 1; i >= 0; --i) {
            for (int j = lt - 1; j >= 0; --j) {
                if (s.charAt(i) == t.charAt(j)) {
                    dp[i][j] = dp[i + 1][j] + dp[i + 1][j + 1];
                }
                else {
                    dp[i][j] = dp[i + 1][j];
                }
            }
        }
        return dp[0][0];
    }
}

留下评论