115. Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S.spa

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).code

Here is an example:
S = "rabbbit"T = "rabbit"orm

Return 3.blog

---rem

DP : 2Dstring

if(T.charAt(i-1) == S.charAt(j-1)) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];  
else dp[i][j] = dp[i][j-1]; 

-
dp[i-1][j-1] + dp[i][j-1];  S(i-1)(j-1)用於T(i-1)(j-1)
- dp[i][j-1]S(i)(j)沒有用於本身T(i-1)(j-1)
public class Solution {
    public int numDistinct(String S, String T) {

        int col = S.length() + 1;  
        int row = T.length() + 1;  
        int[][] dp = new int[row][col];  
        
        // init  
        for(int i = 0; i < row; ++i)  
            dp[i][0] = 0;  
        for(int j = 0; j < col; ++j)  
            dp[0][j] = 1;  
          
        for(int i = 1; i < row; ++i)  
            for(int j = 1; j < col; ++j)  
                if(T.charAt(i-1) == S.charAt(j-1)) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];  
                else dp[i][j] = dp[i][j-1];  
                  
        return dp[row-1][col-1];  
    }
}

 

DP : 1D rotate arrayit

public class Solution {
   public int numDistinct(String S, String T) {
        int[] occurence = new int[T.length() + 1];
        occurence[0] = 1;
        for(int i = 0; i < S.length(); i++){
            for(int j = T.length() - 1; j >= 0 ; j--)
                if(S.charAt(i) == T.charAt(j)){
                    if(occurence[j] > 0)
                        occurence[j + 1] += occurence[j];
                }
        }
        return occurence[T.length()];
    }
}
相關文章
相關標籤/搜索