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
  • 相关阅读:
    LeetCode 023 Merge k Sorted Lists
    LeetCode 022 Generate Parentheses
    LeetCode 020 Valid Parentheses
    LeetCode 019 Remove Nth Node From End of List
    LeetCode 018 4Sum
    LeetCode 017 Letter Combinations of a Phone Number
    Linux常用命令详解(3)
    Linux常用命令详解(2)
    Linux常用命令详解(1)
    部署cobbler服务器
  • 原文地址:https://www.cnblogs.com/superzrx/p/3358338.html
Copyright © 2011-2022 走看看