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相等的个数,如果熟悉《算法导论》的话,可以想到动态规划那一节关于由一个字符串通过增删变成另一个字符串解法

    本题利用动态规划求解

    设决策变量为path[i][j],表示S[1..i]的前i个字符通过删除字符变成T[1..j]的个数

    那么状态转移方程为

                           path[i-1][j-1]  (S[i] == T[j])

    path[i][j] = path[i-1][j](删除S的第i个字符)+                  (不删除字符)

                              0       (S[i] != T[j] )

    class Solution {
    public:
        int numDistinct(string S, string T) {
            int n = S.length(), m=T.length();
            if(n <= m) return S==T;
            vector<vector<int> > path(n+1,vector<int>(m+1,0));
            for(int i = 0; i <=n ; ++ i) path[i][0] = 1;
            for(int j =1; j <= m; ++ j){
                for(int i = 1; i <= n ; ++ i){
                    path[i][j] = path[i-1][j] + (S[i-1]==T[j-1] ? path[i-1][j-1] : 0);
                }
            }
            return path[n][m];
        }
    };
  • 相关阅读:
    JS和jQuery获取节点的兄弟,父级,子级元素
    HTTP协议详解
    HTML5自定义属性对象Dataset
    当你输入一个网址后都发生什么
    javascript实现ajax
    第一次项目总结
    CSS简单布局总结
    animate.css总结
    自定义动画
    CSS 第四天 多重背景 变形 过渡
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3823309.html
Copyright © 2011-2022 走看看