115. Distinct Subsequences

Description

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

Here is an example:
S = "rabbbit", T = "rabbit"

Return 3.

Solution

跟Edit distance思路很像的DP问题。用dp[i][j]代表s.substring(0, i)中t.substring(0, j)的子序列个数。

class Solution {
    public int numDistinct(String s, String t) {
        int m = s.length();
        int n = t.length();
        if (m < n) {
            return 0;
        }
        
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 0; i <= m; ++i) {
            for (int j = 0; j <= n; ++j) {
                if (j == 0) {
                    dp[i][j] = 1;
                } else if (i < j) {
                    dp[i][j] = 0;
                } else {
                    dp[i][j] = dp[i - 1][j];
                    if (s.charAt(i - 1) == t.charAt(j - 1)) {
                        dp[i][j] += dp[i - 1][j - 1];
                    }
                }
            }
        }
        
        return dp[m][n];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,775评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,921评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,936评论 0 0
  • 第一次学会自己讲故事,下午在小区的滑滑梯跟小支、米乐、九九一起玩,不知谁说了一句到处乱跑,于是就突发奇想,说讲一个...
    mark_maggie阅读 272评论 0 0
  • 若不是遇见一场演唱会,我也不知道这般泪水会在何时流淌。 岁月的更迭,字字戳心 时间是个神奇的东西,能巧妙地将很多从...
    jieffey阅读 246评论 0 0