1. DP_LeetCode114. 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.

给定两个字符串S和T,求S有多少个不同的子串与T相同。S的子串定义为在S中任意去掉0个或者多个字符形成的串。

二、解题思路

动态规划,设 dp[i][j] d[i][j]表示S[0....i]中包含多少个和T[0.....j]相同的子串,动态规划方程如下

  • 如果S[i] = T[j], dp[i][j] = dp[i-1][j-1]+dp[i-1 ][j]

  • 如果S[i] 不等于 T[j], dp[i][j] = dp[i-1][j]

  • 初始条件:当T为空字符串时,从任意的S删除几个字符得到T的方法为1

  • dp[0][0] = 1 ; // T和S都是空串.

    dp[1 ... S.length() - 1][0] = 1; // T是空串,S只有一种子序列匹配。

    dp[0][1 ... T.length() - 1] = 0; // S是空串,T不是空串,S没有子序列匹配。

三、解题代码

public int numDistincts(String S, String T){  
  int[][] table = new int[S.length() + 1][T.length() + 1];  
  //initialize data  
  for (int i = 0; i < S.length(); i++)  
      table[i][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)) {  
              table[i][j] += table[i - 1][j] + table[i - 1][j - 1];  
          } else {  
              table[i][j] += table[i - 1][j];  
          }  
      }  
  }  
  return table[S.length()][T.length()];  
}  

下一篇: 2. DP_最长公共子序列

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,418评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,201评论 3 20
  • 想做那种很酷的人吗? 闹铃响了就起,走了就不回头,从来只做喜欢的事情,永远都说一不二,干什么都是雷厉风行…… 答案...
    螃蟹的js阅读 322评论 0 5
  • 什么会在梦中出现 没有路没有山 没有车没有船 更没有别人和聒噪 一片汪洋 就是这个世界最初的一张脸 一汪清冽的水源...
    九月流云阅读 397评论 6 15
  • 我想 想让时间的沙漏停一停 让我回味 回味争吵的路上我会不会后悔 固有的傲慢让我们狼狈不堪 彼此的关爱又显而易见 ...
    小费斯阅读 346评论 0 5