Leetcode Distinct subsequences

Source: Internet
Author: User

Distinct subsequences original problem of leetcode problem solving

Given two strings s and T, find out how many of the cases are from sub-sequences belonging to S. or S can delete its own arbitrary characters, but can not change the relative position of the characters, the total number of deletions can make s into T.

Note the point:

    • Remove any characters including non-deleted characters

Example:

Input: s = "Rabbbit", t = "Rabbit"

Output: 3

Thinking of solving problems

A typical dynamic programming problem, which dp[i][j] represents the number of different sub-sequences of strings s[:i] and t[:j], if s[i-1] and t[j-1] are unequal, then only in s[:i-1] and t[:j], i.e. dp[i][j] = dp[i-1][j]; and when S[i-1] and t[j-1] are equal, either the two characters match exactly, or you can ignore s[i-1], so that t[j-1] matches in s[:i-1], so dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] . Further observation you can compress a two-dimensional array into one dimension, and you only need to calculate from the backward forward.

AC Source
 class solution(object):     def numdistinct(self, S, T):        "" : Type S:str:type t:str:rtype:int "" "m = Len (s) n = len (t) DP = [0  for__inchRange (n +1)] Dp[0] =1         forIinchRange (m): forJinchRange (N-1, -1, -1):ifT[J] = = S[i]: Dp[j +1] + = Dp[j]returndp[-1]if__name__ = ="__main__":assertSolution (). NUMDISTINCT ("Rabbbit","Rabbit") ==3

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

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.