leetcode -- 115. Distinct Subsequences

题目描述

题目难度:Hard

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).

在这里插入图片描述
在这里插入图片描述

解题思路

原文:https://blog.csdn.net/feliciafay/article/details/42959119
动态规划题目。

以S =“rabbbit”,T = "rabbit"为例:
在这里插入图片描述

dp[i][j]表示T的从0开始长度为i的子串和S的从0开始长度为j的子串的匹配的个数。

比如, dp[2][3]表示T中的ra和S中的rab的匹配情况。

(1)显然,至少有dp[i][j] = dp[i][j - 1].

比如, 因为T 中的"ra" 匹配S中的 “ra”, 所以dp[2][2] = 1 。 显然T 中的"ra" 也匹配S中的 “rab”,所以s[2][3] 至少可以等于dp[2][2]。

(2) 如果T[i-1] == S[j-1], 那么dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0);
(注意:T[i-1]表示的是T的前i个字符,因为这里的i是从下标0开始的)

比如, T中的"rab"和S中的"rab"显然匹配,

根据(1), T中的"rab"显然匹配S中的“rabb”,所以dp[3][4] = dp[3][3] = 1,

根据(2), T中的"rab"中的b等于S中的"rab1b2"中的b2, 所以要把T中的"rab"和S中的"rab1"的匹配个数累加到当前的dp[3][4]中。 所以dp[3][4] += dp[2][3] = 2;

(3) 初始情况是
dp[0][0] = 1; // T和S都是空串.
dp[0][1 … S.length() ] = 1; // T是空串,S只有一种子序列匹配。
dp[1 … T.length() ][0] = 0; // S是空串,T不是空串,S没有子序列匹配。

AC代码

class Solution {
   public int numDistinct(String S, String T) {
    // array creation
    int[][] mem = new int[T.length()+1][S.length()+1];

    // filling the first row: with 1s
    for(int j=0; j<=S.length(); j++) {
        mem[0][j] = 1;
    }
    
    // the first column is 0 by default in every other rows but the first, which we need.
    
    for(int i=1; i<=T.length(); i++) {
        for(int j=1; j<=S.length(); j++) {
            if(T.charAt(i - 1) == S.charAt(j - 1)) {
                mem[i][j] = mem[i - 1][j - 1] + mem[i][j - 1];
            } else {
                mem[i][j] = mem[i][j - 1];
            }
        }
    }
    
    return mem[T.length()][S.length()];
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值