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只通过删除操作进行变换的方法数(通过从S中删去几个字符变成T的方法)

    通过动归,对S前i位与T前j位的情况 考虑均新增一位会如何变化

    class Solution {
    public:
        int numDistinct(string S, string T) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<vector<int> > count;
            if(S.length()<T.length())return 0;
            count.resize(S.length()+1);
            for(int i=0;i<=S.length();i++){
                count[i].resize( min(i,(int)T.length()) +1);
                count[i][0]=1;
            }
            for(int i=1;i<=S.length();i++)
            {
                if(count[i].size()==i+1){
                    int j=1;
                    for(;j<count[i].size()-1;j++){
                        if(S[i-1]==T[j-1]){
                            count[i][j]=count[i-1][j-1]+count[i-1][j];
                        }
                        else{
                            count[i][j]=count[i-1][j];
                        }
                    }
                    if(S[i-1]==T[j-1]){
                        count[i][j]=count[i-1][j-1];
                    }
                    else{
                        count[i][j]=0;
                    }
                }
                else{
                    int j=1;
                    for(;j<count[i].size();j++){
                        if(S[i-1]==T[j-1]){
                            count[i][j]=count[i-1][j-1]+count[i-1][j];
                        }
                        else{
                            count[i][j]=count[i-1][j];
                        }
                    }
                }
            }
            return count[S.length()][T.length()];
        }
    };
    View Code
  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/superzrx/p/3358338.html
Copyright © 2011-2022 走看看