Title Description:
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, "ACE" is a subsequence of "ABCDE" while "AEC" was not).
Here are an example:
S = "Rabbbit", T = "Rabbit"
Return 3.
The question was not understood at first, and it was asked to find out the different number of subsequence in S and T. Read it a few times and found
is not the number of sub-sequences, but to ask, for S, how many different kinds of delete operations can get t? So
The question is not the number of different sub-sequences, but the different number of delete operations。 (according to the example of the topic, s can be changed to T through 3 different deletions)
Ideas:
String analysis on topic: S = "Rabbbit" t= "Rabbit"
Cannot find any strings when s is empty
When T is empty, the operand is 1, which is delete all
First look at the case of S = "R",
s = "r" t = "R" Return 1
s = "r" t = "ra", "Rab", "Rabb" ... return 0, because no matter the deletion, s cannot become t
When you look at the case of s = "Ra", t = "Ra", to calculate the s= "RA" and t= "RA" of the different deletion operands, it is equal to ask:
S= "R" and t= "RA" when different delete operand (0), then compare if s last 1 bits (a) ==t the last one (a), then need to add s== "R" and t== "R" of different operands (1).
This problem has a recursive relationship, consider DP.
Get the recursive formula:
if s[i-1] = = T[i-1]:
DP[I][J] = Dp[i-1][j-1] + dp[i-1][j]
else:
DP[I][J] = Dp[i-1][j]
Implementation code:
public class Solution {public int numdistinct (string s, String t) { if (string. Isnullorwhitespace (s)) {return 0;} if (string. Isnullorwhitespace (t)) {return 1;} var dp = new Int[s.length+1,t.length + 1];for (var i = 0;i < s.length + 1; i++) {dp[i,0] = 1;} for (var j = 1; J < T.length + 1; j + +) {Dp[0,j] = 0;} for (var i =1; i < s.length + 1, i++) {for (var j = 1; J < T.length + 1; + j) {if (s[i-1] = = T[j-1]) {dp[i,j] = Dp[i-1,j] + dp[i-1,j-1];} ELSE{DP[I,J] = Dp[i-1,j];}} Return dp[s.length, T.length]; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Distinct subsequences