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.

給定兩個(gè)字符串S和T,求S有多少個(gè)不同的子串與T相同。S的子串定義為在S中任意去掉0個(gè)或者多個(gè)字符形成的串。

二、解題思路

動(dòng)態(tài)規(guī)劃,設(shè) dp[i][j] d[i][j]表示S[0....i]中包含多少個(gè)和T[0.....j]相同的子串,動(dòng)態(tài)規(guī)劃方程如下

  • 如果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]

  • 初始條件:當(dāng)T為空字符串時(shí),從任意的S刪除幾個(gè)字符得到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_最長公共子序列

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網(wǎng)事_79a3閱讀 12,923評論 3 20
  • 想做那種很酷的人嗎? 鬧鈴響了就起,走了就不回頭,從來只做喜歡的事情,永遠(yuǎn)都說一不二,干什么都是雷厲風(fēng)行…… 答案...
    螃蟹的js閱讀 385評論 0 5
  • 什么會(huì)在夢中出現(xiàn) 沒有路沒有山 沒有車沒有船 更沒有別人和聒噪 一片汪洋 就是這個(gè)世界最初的一張臉 一汪清冽的水源...
    九月流云閱讀 422評論 6 15
  • 我想 想讓時(shí)間的沙漏停一停 讓我回味 回味爭吵的路上我會(huì)不會(huì)后悔 固有的傲慢讓我們狼狽不堪 彼此的關(guān)愛又顯而易見 ...
    小費(fèi)斯閱讀 397評論 0 5

友情鏈接更多精彩內(nèi)容