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, de >"ACE"de> is a subsequence of de >"ABCDE"de> while de >"AEC"de> is not).

Here is an example:
S = de >"rabbbit"de>, T = de >"rabbit"de>

Return de >3de>.


用动态规划思想,从两个字符串的最后往前计算匹配数目,record[i][j]表示T从i到末尾,S从j到末尾的匹配数是多少。我以i为外部循环,则逻辑可以理解为,首先计算长度为1的目标串在源串中的匹配数,然后计算长度为2的目标串在源串中的匹配数,逐渐加长目标串。

如果T的第i个字符与S的第j个字符相同,那么此时的匹配数由两部分构成:

首先是算上S[j]的情况下,S从j到末尾匹配T从i到末尾的数目,即T从i+1到末尾,S从j+1到末尾的匹配数,即record[i+1][j+1]

然后是不算S[j],S从j到末尾匹配T从i到末尾的数目,即record[i][j+1]

因此,主要的递推公式为record[i][j] = record[i + 1][j + 1] + record[i][j + 1];

考虑目标串长度为1的情况,若源串长度也为1,则record[i][j] = 1;

若源串长度不为1,上述两种情况的前者一定为1,因此record[i][j] = 1 + record[i][j + 1];

综上,代码如下:

class Solution {
    public int numDistinct(String s, String t) {
        int slen = s.length(), tlen = t.length();
        if(tlen == 0)
        	return 1;
        if(slen == 0)
        	return 0;
        int[][] record = new int[tlen][slen];
        char[] sou = s.toCharArray(), tar = t.toCharArray();
        for(int i = tlen - 1; i > -1; i--){
        	for(int j = slen - 1; j > -1; j--){
        		if(tar[i] == sou[j]){
        			if(i < tlen - 1 && j < slen - 1)
        				record[i][j] = record[i + 1][j + 1] + record[i][j + 1];
        			if(i == tlen - 1 && j == slen - 1)
        				record[i][j] = 1;
        			if(i == tlen - 1 && j < slen - 1)
        				record[i][j] = 1 + record[i][j + 1];
        		}
        		else if(j < slen - 1)
        			record[i][j] = record[i][j + 1];
        	}
        }

        return record[0][0];
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值