zoukankan      html  css  js  c++  java
  • Leetcode-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.

    Analysis:

    We definte the state d[i][j] as the number of distinct subseq of T[0...j-1] in S[0...i-1]. For d[i][j], we have two operations: 1. Retain the char S[i-1], 2. Delete the char S[i-1]. For each d[i][j], we have two different situations:

    1. S[i-1]!=T[j-1]: The only operation we can do is deleting the char S[i-1], otherwise, we cannot get a sequence T[0..j-1] in S[0...i-1]. Then d[i][j] equals to the number of dseq of T[0...j-1] in S[0...i-2], because for each of such cases, we delete the S[i-1] and we will get one case for d[i][j].

    2. S[i-1]==T[j-1]: We can do either of the two operations. For deleting operation, d[i][j] = d[i-1][j]. For retainning operation, we then consider the cases for d[i-1][j-1]. For each of such cases, we retain the char S[i-1] and we will get one case in d[i][j]. As a result, d[i][j]=d[i-1][j]+d[i-1][j-1].

    To summrize, after defining the state, we should start from what kind of operations we can do at current state, and identify different situations and the operations can be done in each situtaion.

    Solution:

     1 public class Solution {
     2     public int numDistinct(String S, String T) {
     3         int len1 = S.length();
     4         int len2 = T.length();
     5 
     6         int[][] d = new int[len1+1][len2+1];
     7         for (int i=0;i<=len1;i++) Arrays.fill(d[i],0);
     8         for (int i=0;i<=len1;i++) d[i][0] = 1;
     9 
    10         for (int i=1;i<=len1;i++){
    11             int end = i;
    12             if (end>len2) end = len2;
    13             for (int j=1;j<=end;j++)
    14                 if (S.charAt(i-1)!=T.charAt(j-1))
    15                     d[i][j] = d[i-1][j];
    16                 else d[i][j] = d[i-1][j]+d[i-1][j-1];
    17         }
    18 
    19         return d[len1][len2];        
    20     }
    21 }
  • 相关阅读:
    【雕爷学编程】MicroPython动手做(01)——春节后入手了K210开发板
    【雕爷学编程】零基础Python(01)---“投机取巧”的三条途径
    【雕爷学编程】Arduino动手做(64)---RGB全彩LED模块
    Microsoft Development Platform Technologies
    JS 的Date对象
    SQL数据库连接池与C#关键字return
    RDLC报表 报表数据 栏 快捷键
    C# 操作World生成报告
    SAP-ABAP系列 第二篇SAP ABAP开发基础
    SAP-ABAP系列 第一篇SAP简介
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4122816.html
Copyright © 2011-2022 走看看