zoukankan      html  css  js  c++  java
  • [leedcode 115] 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.

    public class Solution {
        public int numDistinct(String s, String t) {
            //这种题优先选择动态规划,推导公式非常重要,注意dp[i][j]的含义:
            //代表s中的i个字母,和t中的j个字母,s包含t的个数,
            //判断s中第i个字符是否等于t中第j个字符,如果相等,根据是否包含t[j-1]分两种情况:dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
            int sl=s.length();
            int tl=t.length();
            int dp[][]=new int[sl+1][tl+1];
            for(int i=0;i<=sl;i++){
                dp[i][0]=1;
            }
            for(int j=1;j<=tl;j++){
                dp[0][j]=0;
            }
            
            for(int i=1;i<=sl;i++){
                for(int j=1;j<=tl;j++){
                    if(i<j){
                        dp[i][j]=0;break;
                    }
                    if(s.charAt(i-1)!=t.charAt(j-1)){
                        dp[i][j]=dp[i-1][j];
                    }else{
                        dp[i][j]=dp[i-1][j]+dp[i-1][j-1];
                    }
                    
                }
            }
            return dp[sl][tl];
        }
    }
  • 相关阅读:
    WCF开发笔记 高版本.Net的坑
    Net Start可以加载驱动
    解决:Windows 2008远程黑屏问题
    Visual Studio 解决方案版本从v12-->v14
    Visual Studio 使用之禁用/启用模板警告
    Windows 10 常用的快捷键及常用指令
    git
    Socket通信原理 很好
    java集合
    JavaEE简介
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4668602.html
Copyright © 2011-2022 走看看