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
  • 相关阅读:
    扩展中国剩余定理学习笔记
    寻找宝藏
    卢卡斯定理学习笔记
    [国家集训]矩阵乘法
    中国剩余定理学习笔记
    [CTSC2018]混合果汁
    数据结构(C语言版)第二章2.82.11 动态链表
    数据结构(C语言版)第二章2.12.7
    C语言中换行符和回车符的区别(转)
    C的xml编程libxml2(转摘)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3358338.html
Copyright © 2011-2022 走看看