[Leetcode] Distinct subsequences @ Python

Source: Internet
Author: User

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

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.