LeetCode - Distinct Subsequences

題目:spa

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

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

Here is an example:
S = "rabbbit", T = "rabbit" blog

Return 3. rem

思路:string

動態規劃;關鍵是如何獲得遞推關係,能夠這樣想,設母串的長度爲 j,子串的長度爲 i,咱們要求的就是長度爲 i 的字串在長度爲 j 的母串中出現的次數,設爲 dp[i][j],若母串的最後一個字符與子串的最後一個字符不一樣,則長度爲 i 的子串在長度爲 j 的母串中出現的次數就是母串的前 j - 1 個字符中子串出現的次數,即 dp[i][j] = dp[i][j - 1],若母串的最後一個字符與子串的最後一個字符相同,那麼除了前 j - 1 個字符出現字串的次數外,還要加上子串的前 i - 1 個字符在母串的前 j - 1個字符中出現的次數,即dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]。  it

package dp;

public class DistinctSubsequences {

    public int numDistinct(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        if (tlen > slen) return 0;
        int[][] dp = new int[slen + 1][tlen + 1];
        for (int i = 0; i <= slen; ++i) {
            for (int j = 0; j <= tlen; ++j) {
                if (j == 0) {
                    dp[i][j] = 1;
                    continue;
                }
                
                if (j > i) {
                    dp[i][j] = 0;
                    continue;
                }
                
                if (s.charAt(i - 1) == t.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
                else
                    dp[i][j] = dp[i - 1][j];                
            }
        }
        return dp[slen][tlen];
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DistinctSubsequences d = new DistinctSubsequences();
        System.out.println(d.numDistinct("rabbbit", "rabbit"));
    }

}
相關文章
相關標籤/搜索