Problem 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, is a subsequence of and is not "ACE"
"ABCDE"
"AEC"
).
Here are an example:
S = "rabbbit"
, T ="rabbit"
Return 3
.
Basic idea:
Dynamic planning methods. To find a recursive type:
F (s,t) = f (s-1,t-1) +f (s-1,t) (when the last character of S is the same as the last character of T)
F (s,t) = f (s-1,t) (when the last character of S is different from the last character of T)
Code:
public int numdistinct (string S, String T) {//java if (s.length () < T.length ()) return 0; int sizeS = S.length (); int sizet = T.length (); if (SizeS = = Sizet) {if (S.equals (T)) return 1; else return 0; } if (Sizet = = 0) return 1; int [] [] array = new Int[sizes+1][sizet]; for (int i = 0; i < Sizet; i++) array[0][i] = 0; Char fch = t.charat (0); for (int i = 1; I <=sizeS; i++) {if (fch = = S.charat (i-1)) array[i][0] = array[i-1][0]+ 1; else array[i][0] = array[i-1][0]; } for (int i = 1; I <=sizeS; i++) {Char sch = S.charat (i-1); for (int j = 1; J <sizeT; J + +) {char tch = T.charat (j); if (tch = = Sch) Array[i][j] = Array[i-1][j-1]+array[i-1][J]; else array[i][j] = array[i-1][j]; }} return array[sizes][sizet-1]; }
[Leetcode] Distinct subsequences