[leetcode] 115.Distinct Subsequences

题目:
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 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).

Here is an example:
S = “rabbbit”, T = “rabbit”

Return 3.
题意:
给定一个字符串S和T,计算T在S中的所有子序列个数。子序列不是子串,无需连续。
思路:
这道题采用动态规划思想。保存二维数组DP[i][j] 其中i代表的是匹配到T的下标i的字符,j代表时从S的下标0到下标j,即j+1长度的字符串拥有的T的前i+1字符串的子序列的个数。首先必须是j >= i,不然S中的字符个数都没有T中的多的话,肯定无法从前j+1个中找出前i+1的字符的子串。如果T[i] == S[j]的话,那么转移方程就是DP[i][j] = DP[i-1]j-1] + DP[i][j-1].即S的第j+1个字符是否用作在匹配T的子序列中。如果T[i] != S[j]的话,那么DP[i][j] = DP[i][j-1];
具体来说转移方程如下:

  1. DP[i][j] = DP[i-1][j-1] + DP[i][j-1] { T[i] == S[j])
  2. DP[i][j] = DP[i][j-1]{T[i] != S[j]}
    其中关于具体的细节请参考代码:
    以上。
    代码如下:
class Solution {
public:
    int numDistinct(string s, string t) {
        if(s.size() < t.size() || t.size() == 0)return 0;
        DP = new int*[t.size()];
        for(int i = 0; i < t.size(); i++){
            DP[i] = new int[s.size()];
        }
        for(int i = 0; i < t.size(); i++)
            for(int j = i; j < s.size() - (t.size() - i - 1); j++){
                if(t[i] == s[j]){
                    DP[i][j] = ((i > 0)?DP[i-1][j-1]:1) + ((j > i)?DP[i][j-1]:0);
                }  
                else{
                    DP[i][j] = ((i == j)?0:DP[i][j-1]);
                }
            }
        return DP[t.size() - 1][s.size() - 1];
    }
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值