第42题 Distinct Subsequences

本文介绍了一种使用动态规划算法来计算字符串S中字符串T的不同子序列的数量的方法。通过实例演示了如何通过比较两个字符串的字符并跟踪可能的状态转移来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Hide Tags
  Dynamic Programming String










Code in Java:
public class Solution {
    public int numDistinct(String S, String T) {
        //count the number of ways to convert S to T by deleting some characters in S.
         if(S.length()==0&&T.length()==0)   return 0;
         if(S.length()<T.length()) return 0;
         int lenS = S.length(), lenT = T.length();
         
         //Use opj[i][j] to represent the number of ways to convert S[0...i-1] to T[0...j-1]
         //So opj[lenS][lenT] is the total number of ways to convert S to T
         int[][] opj = new int[lenS+1][lenT+1];
         
         //opj[i][0] represents the number of ways to convert S[0...i-1] to an empty string
         //so for any string, there is only one ways, which is deleting all the characters
         for(int i=0; i<lenS+1; i++)
            opj[i][0]=1;
        
        //There are two possibilities when computing opj[i][j] from S[0...i-1] to T[0...j-1]:
        //if S[i-1]==T[j-1], we can obtain opj[i][j] by either remaining or deleting S[i-1]
        //  if remain S[i-1]:   opj[i][j]=opj[i-1][j-1] 
        //                      the number of ways from  S[0...i-1] to T[0...j-1]=the number of ways
        //                      from S[0...i-2] to T[0...j-2]
        //  if delete S[i-1]:   opj[i][j]=opj[i-1][j]
        //                      the number of ways from S[0...i-1] to  T[0...j-1]=the number of ways
        //                      from S[0...i-2] to T[0...j-1]
        //if S[i-1]!=T[j-1], there is only one way to obtain opj[i][j], wo we have
        //      opj[i][j] = opj[i-1][j]
        //      the number of ways from S[0...i-1] to T[0...j-1]=the nubmer of ways from 
        //      S[0...i-2] to T[0...j-1]
        for(int i=1; i<lenS+1; i++){
            for(int j=1; j<lenT+1&&j<=i; j++){
                opj[i][j] = S.charAt(i-1)==T.charAt(j-1)?opj[i-1][j-1]:0;
                if(i-1>=j)  opj[i][j]+= opj[i-1][j];
            }
        }
        return opj[lenS][lenT];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值