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.


    题解:题目要求的是S中有多少不同的字串与T相同。

    用DP求解。建立二维数组dp[i][j]表示S(0,i-1)有多少不同的字串与T(0,j-1)相同。则:

    1. 当T为空串时,S必然有字串和T匹配,所以dp[i][0] = 1;
    2. 当S为空串时,若T不为空串,则S任意字串必然不同于T,所以dp[0][i] = 0(i != 0);
    3. 当S和T都为空串的时候,匹配,所以dp[0][0] = 1;
    4. 其他情况dp[i][j] = dp[i-1][j] + (S[i-1] == T[j-1]? dp[i-1][j-1] : 0);

    第4中情况理解如下:

    如上图所示,不管T[i]是否等于s[j],S[0,i-1]中和T[0,j]相同的字串一定包含在S[0,i]中,所以dp[i][j] 至少为 dp[i-1][j];

    而如果s[i] = T[j],那么在S[0,i-1]中包含的T[0,j-1]加上T[j],就是S[0,i]中等于的T[0,j]的字串,所以如果s[j] = T[i],dp[i][j] = dp[i-1][j] + dp[i-1][j-1];

    代码如下:

     1 public class Solution {
     2     public int numDistinct(String S, String T) {
     3         if(S == null || T == null)
     4             return 0;
     5         int m = S.length();
     6         int n = T.length();
     7         int[][] dp = new int[m+1][n+1];
     8         
     9         dp[0][0] = 1;
    10         for(int i = 1;i <= m;i++)
    11             dp[i][0] = 1;
    12         
    13         for(int i= 1;i<=m;i++){
    14             for(int j = 1;j <= n;j++){
    15                 dp[i][j] = dp[i-1][j];
    16                 dp[i][j] += S.charAt(i-1) == T.charAt(j-1)?dp[i-1][j-1]:0; 
    17             }
    18         }
    19         
    20         return dp[m][n];
    21     }
    22 }
  • 相关阅读:
    理解Express express.static 和 __direname 及 __firename的含义
    HTTP请求中 request payload 和 formData 区别?
    POST提交数据之---Content-Type的理解;
    前端域名访问页面中的一些配置项
    使用Nginx来解决跨域的问题
    vue-resource get/post请求如何携带cookie的问题
    socket实现聊天功能(二)
    go语言之进阶篇通过结构体生成json
    go语言之进阶篇JSON处理
    go语言之进阶篇正则表达式
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3862415.html
Copyright © 2011-2022 走看看