首页 > 代码库 > 【leetcode刷题笔记】Distinct Subsequences

【leetcode刷题笔记】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相同。

用DP求解。建立二维数组dp[i][j]表示S(0,i-1)有多少不同的字串与T(0,j-1)相同。则:

  1. 当T为空串时,S必然有字串和T匹配,所以dp[i][0] = 1;
  2. 当S为空串时,若T不为空串,则S任意字串必然不同于T,所以dp[0][i] = 0(i != 0);
  3. 当S和T都为空串的时候,匹配,所以dp[0][0] = 1;
  4. 其他情况dp[i][j] = dp[i-1][j] + (S[i-1] == T[j-1]? dp[i-1][j-1] : 0);

第4中情况理解如下:

如上图所示,不管T[i]是否等于s[j],S[0,i-1]中和T[0,j]相同的字串一定包含在S[0,i]中,所以dp[i][j] 至少为 dp[i-1][j];

而如果s[i] = T[j],那么在S[0,i-1]中包含的T[0,j-1]加上T[j],就是S[0,i]中等于的T[0,j]的字串,所以如果s[j] = T[i],dp[i][j] = dp[i-1][j] + dp[i-1][j-1];

代码如下:

 1 public class Solution { 2     public int numDistinct(String S, String T) { 3         if(S == null || T == null) 4             return 0; 5         int m = S.length(); 6         int n = T.length(); 7         int[][] dp = new int[m+1][n+1]; 8          9         dp[0][0] = 1;10         for(int i = 1;i <= m;i++)11             dp[i][0] = 1;12         13         for(int i= 1;i<=m;i++){14             for(int j = 1;j <= n;j++){15                 dp[i][j] = dp[i-1][j];16                 dp[i][j] += S.charAt(i-1) == T.charAt(j-1)?dp[i-1][j-1]:0; 17             }18         }19         20         return dp[m][n];21     }22 }