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