2015年5月11日星期一

Distinct Subsequences leetcode

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的子串定义为在S中任意去掉0个或者多个字符形成的串。
  0 r a b b b i t
1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
a 0 1 1 1 1
b 0 0 2 3 3 3
b 0 0 0 0 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3  
state: dp[i][j] 表示S串中从开始位置到第i位置与T串从开始位置到底j位置匹配的子序列的个数
function: dp[i][j] = dp[i][j-1] 就是说假设S已经匹配了j-1个字符,无论S[j]和T[i]是否匹配, 至少是dp[i][j-1]
如果匹配, 我们可以让S[j]和T[i]匹配,然后让S[j - 1]和T[i - 1]去匹配 (由图得关系)
dp[i][j] += dp[i-1][j-1]
initial: f[i][0] = 0 f[0][j] = 1 空集也是subsequences
return dp[m][n]
时间和空间都是O(m * n)

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

没有评论:

发表评论