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
  • 相关阅读:
    Project项目视图
    Console(控制台视图)
    Layout布局列表
    Layers层列表
    帐户下拉
    TransformGizmo(变换)切换
    Play播放控件
    变换工具
    工具栏
    Help帮助
  • 原文地址:https://www.cnblogs.com/superzrx/p/3358338.html
Copyright © 2011-2022 走看看