1. 程式人生 > >動態規劃之115 Distinct Subsequences

動態規劃之115 Distinct Subsequences

題目連結:https://leetcode-cn.com/problems/distinct-subsequences/description/

參考連結:https://www.cnblogs.com/springfor/p/3896152.html

     http://blog.csdn.net/abcbc/article/details/8978146

dp[i][j]:S使用前i個字元,T使用前面j個字元。dp[0][0]使用S前0個字元,使用T前0個字元。

當T為空的時候,空字串是任何S串的字串。

當S為空的時候,任何字元都不是其的字串。

下圖是S="rabbbit",T="rabbit"。

狀態轉移方程:

if (S.charAt(i - 1) != T.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j];
}
if (S.charAt(i - 1) == T.charAt(j - 1))
dp[i][j] = dp[i - 1][j]+dp[i - 1][j - 1];

如圖所示:黃色部分是二者相等的,黑色部分是二者不想等的情況。

程式碼如下所示:

public int numDistinct(String S, String T) {
        int[][] dp = new int[S.length() + 1][T.length() + 1];
        dp[
0][0] = 1;//initial for(int j = 1; j <= T.length(); j++)//S is empty dp[0][j] = 0; for (int i = 1; i <= S.length(); i++)//T is empty dp[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)) { dp[i][j] = dp[i - 1][j]; } if (S.charAt(i - 1) == T.charAt(j - 1)) dp[i][j] = dp[i - 1][j]+dp[i - 1][j - 1]; } } return dp[S.length()][T.length()]; }