[Leetcode] Distinct subsequences

Source: Internet
Author: User

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)


 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.