【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值