【LeetCode每天一题】Distinct Subsequences(不同的子序列)

Given a string S and a string T, count the number of distinct subsequences of S which equals T。A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).




















思路

  在看到这道题的时候我第一时间想到了递归的方式进行解决,主要方法是加入S=“babgbag”,T=“bag”。我们现在S中找到第一个与T中第一个字符相等的位置。然后进行下一次递归的时候S="abgbag", T="ag",然后再找到相同的第一个位置。这时S="bgbag", T="g"。当T只有一个字符时,再剩余的S字符串中找出T中的字符所包含的次数遍历完毕之后回到上一层继续找相等为位置。以直到结束为止。
解决代码


 1 class Solution(object):
 2     def numDistinct(self, s, t):
 3         """
 4         :type s: str
 5         :type t: str
 6         :rtype: int
 7         """
 8         if not s or not t:
 9             return 0
10         res = [0]
11         self.findcount(s, t, res)
12         return res[0]
13            
16     def findcount(self, s, t, res):
17         if len(s) == 0 or len(t) == 0:   # 其中一个字符串为空时直接返回
18             return 
19         if len(t) == 1:                 # 当T中元素个数为1时,进行遍历得到再S串中的个数。
20             for i in s:
21                 if i == t:
22                     res[0] += 1
23             return
24         for i in range(len(s)):           # 从头开始遍历查找s中第一个元素与T中第一个元素相等的位置。
25             if s[i] == t[0]:
26                 self.findcount(s[i+1:], t[1:], res) 
原文地址:https://www.cnblogs.com/GoodRnne/p/10890276.html