leetcode_115-- different sequences (Java implementation)

 Topic links:

https://leetcode-cn.com/problems/distinct-subsequences/submissions/

 

Ideas:

A title dp

State transition equation is:

if (s [j] == t [i]) dp [i] [j] = dp [i-1] [j-1] = dp [i] [j-1] // meaning: If the string the same as the corresponding character, transfer status, the number of sub-sets of strings before this appeared in the substring is the number of times a substring that appear on the plus before the number of occurrences of the string (do not know did not make it clear, I understand / thinking)

else dp [i] [j] = dp [i] [j-1], if not equal, in this cell must be the number of the current substring occurring in the set, i.e. on a cell's value (because no new same string)

Forms illustrated as follows:

(Empty string certainly appear once in all sub-string, and the first column because the original string is empty, there is no corresponding appearance - bad language, loud noise may not be clear, but because of the plug-understand / Behind his. )

t \ s '' b a b g b a g
'' 1 1 1 1 1 1 1 1
b 0 1 1 2 2 3 3 3
a 0 0 1 1 1 1 4 4
g 0 0 0 0 1 1 1 5

 

 

 

 

Here is the source code:

package leetcode;

public class NumDistinct {
    /**
     * dynamic programming
     * @param s
     * @param t
     * status transfer formula is :
     * if s==t dp[i][j] = dp[i-1][j-1] + dp[i][j-1]:means the sum of combinations and already exist
     * if s!=t dp[i][j] = dp[i][j-1]
     * @return
     */
    public int numDistinct(String s, String t) {
        if(s.length()==0&&t.length()==0)return 0;
        int[][] dp = new int[t.length()+1][s.length()+1];//build status transfer array
        for(int i = 0;i<dp.length;++i){
            dp[i][0] = 0;
        }
        for(int j = 0;j<dp.length;++j){
            dp[0][j] = 1;
        }//initialize
        char[] s_temp = s.toCharArray();
        char[] t_temp = t.toCharArray();
        for(int i = 1;i<dp.length;++i){
            for(int j = 1;j<dp[0].length;++j){
                if(t_temp[i-1]==s_temp[j-1])
                    dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
                else
                    dp[i][j] = dp[i][j-1];
            }
        }
        return dp[s.length()][t.length()];
    }
}

 

Code has been ac

I hope to be helpful

the above

Guess you like

Origin www.cnblogs.com/lavender-pansy/p/12525950.html