[LeetCode][Java] Distinct Subsequences

來源:互聯網
上載者:User

標籤:leetcode   java   distinct subsequence   

題目:

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 ,統計T作為S的子序列共有多少種。

這裡定義的字串的一個子序列是指,在原字串中在保持原相對字母順序的前提下,刪除一些(可以為0 )字元。(例如,"ACE" 是"ABCDE"的子序列,而"AEC"不是)

這裡給出一個例子:

S = "rabbbit", T = "rabbit"

Return 3.

演算法分析:

 DP 動態規劃

 首先設定動態規劃數組dp[i][j],表示S串中從開始位置到第i位置與T串從開始位置到底j位置匹配的子序列的個數。

 如果S串為空白,那麼dp[0][j]都是0;

 如果T串為空白,那麼dp[i][j]都是1,因為空白串為是任何字串的字串。

如果S的第i個字元與T的第j個字元不同,則res[i][j]的序列個數應該與res[i-1][j]的個數相同;

如果S的第i個字元與T的第j個字元相同,那麼除了要考慮res[i-1][j-1]的個數情況,還要考慮res[i-1][j]的個數;

因此,遞推式定義如下:

if(S.charAt(i)==T.charAt(j))  

res[i][j]=res[i-1][j-1]+res[i-1][j];

else res[i][j]=res[i-1][j];


AC代碼:
public class Solution {    public int numDistinct(String S, String T)     {        //採用動態規劃的思想,定義維護量res[i][j]:表示S的前i個元素和T的前j個元素能夠匹配的轉化方式       int[][] res = new int[S.length() + 1][T.length() + 1];           res[0][0] = 1;//initial        //進行初始化       for(int j = 1; j <= T.length(); j++)//S is empty              res[0][j] = 0;       for (int i = 1; i <= S.length(); i++)//T is empty              res[i][0] = 1;        for(int i=1;i<S.length()+1;i++)        {            for(int j=1;j<T.length()+1;j++)            {                if(S.charAt(i-1)==T.charAt(j-1))                    res[i][j]=res[i-1][j-1]+res[i-1][j];                else                    res[i][j]=res[i-1][j];            }        }        return res[S.length()][T.length()];    }}

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Distinct Subsequences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.