Original title address: https://oj.leetcode.com/problems/distinct-subsequences/
Test instructions
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 was formed from the original string by deleting some (can be none) of the C Haracters without disturbing the relative positions of the remaining characters. (ie, is a subsequence of and is not "ACE" "ABCDE" "AEC" ).
Here are an example:
S = "rabbbit" , T ="rabbit"
Return 3 .
Problem solving: This problem is solved by using dynamic programming. In all substrings of S, the number of substrings in the string is T. Here's a look at the state transition equation. DP[I][J] means how many substrings in s[0...i-1] are t[0...j-1].
When S[i-1]=t[j-1]: dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
S[0...I-1] How many substrings are t[0...j-1] containing: {s[0...i-2] How many substrings are in t[0...j-2]}+{s[0...i-2] and how many substrings are t[0...j-1]}
When S[i-1]!=t[j-1]: dp[i][j]=dp[i-1][j-1]
How is the initialization state determined:
Dp[0][j]=0; because: S is an empty string, it cannot contain a non-empty substring anyway. This initial state is included in the initialization of the matrix DP, incidentally.
Dp[i][0]=1; because: s[0...i-1] only one substring is an empty string.
Code:
classSolution:#@return An integer defnumdistinct (self, S, T): DP= [[0 forJinchRange (len (T) + 1)] forIinchRange (len (S) + 1) ] forIinchRange (len (S) + 1): dp[i][0]= 1 forIinchRange (1, len (S) + 1): forJinchRange (1, len (T) + 1): ifS[i-1] = = T[j-1]: dp[i][j]= Dp[i-1][j-1] + dp[i-1][j]Else: Dp[i][j]= Dp[i-1][j]returnDp[len (S)][len (T)]
[leetcode]distinct subsequences @ Python