標籤: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