115. Dynamic programming of different subsequence strings

First of all, seeing the problem of substrings, it is easy for us to think of creating a dynamic array of dp [s1.length ()] [s2.length ()]. ​​Let ’s look at the question below:

 

I thought that during normal traversal, if we set a mark, it would be easier to mark the situation we have encountered before. For example, when we encounter the first b, we thought that if the preceding character There are two cases, we judge that if the current character matches the expected one, then we need to add the previous character to the situation generated by this character, that is, dp [i] [j] = dp [i-1] [ j-1] + dp [i] [j-1], if the match is unsuccessful, then we only record the occurrence of this character, without considering the previous character, that is, dp [i] [j] = dp [ i] [j-1]. Then we found the state transition equation and listed the code:

    public int numDistinct(String s, String t) {
        int[][] dp=new int[t.length()+1][s.length()+1];
        for(int i=0;i<t.length()+1;i++){
            for(int j=0;j<s.length()+1;j++){
                if(i==0) {
                    dp[i][j]=1;
                    continue;
                }
                if(j==0) {
                    dp[i][j]=0;
                    continue;
                }
                if(s.charAt(j-1)==t.charAt(i-1)){
                    dp[i][j]=dp[i-1][j-1]+dp[i][j-1];
                }
                else dp[i][j]=dp[i][j-1];
            }
        }
        return dp[t.length()][s.length()];
    }

Note that each line is the conversion state of this character, so we have to traverse the string of S every time.

Published 17 original articles · praised 0 · visits 151

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105058346