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 }
  • 相关阅读:
    FilterLog代码分析
    Session
    关于XML的技术详情----XML定义 用途 工作原理及未来
    javaee思维导图
    互联网应用与企业级应用的区别
    javaee课程目标
    Recycle -- 项目总结
    python3.6学习笔记2基础语法
    python3.6学习笔记1认识python
    CentOS6.5下Virtualenv搭建Python3开发环境
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4122816.html
Copyright © 2011-2022 走看看