LeetCode-115 Distinct Subsequences

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.

 

题目要求计算T在S的子序列中出现的次数,这里的子序列只要求顺序与在S中的相对顺序一致就行。

思路:使用动态规划解题。

设map[i][j]表示S[0~i]的子序列中出现T[0~j]的次数,则:

1. 如果S[i] != T[j],则map[i][j] = map[i-1][j]

2. 如果S[i] == T[j],则map[i][j] = map[i-1][j-1] + map[i-1][j];

代码如下:

public int numDistinct(String S, String T) {
        if(S == null || S.length() == 0)
            return 0;
        if(T == null || T.length() == 0)
            return 1;
        if(S.length() < T.length())
            return 0;
        
        int map[][] = new int[S.length()][T.length()];
        if(S.charAt(0) == T.charAt(0))
            map[0][0] = 1;
        for(int i=1; i<S.length(); i++) {
            if(S.charAt(i) == T.charAt(0))
                map[i][0] = map[i-1][0] + 1;
            else {
                map[i][0] = map[i-1][0];
            }
        }
        
        for(int i=1; i<S.length(); i++) {
            for(int j=1; j<=i && j<T.length(); j++) {
                if(S.charAt(i) == T.charAt(j)) {
                    map[i][j] = map[i-1][j-1] + map[i-1][j];
                } else {
                    map[i][j] = map[i-1][j];
                }
            }
        }
        return map[S.length()-1][T.length()-1];
    }

 

posted on 2015-03-12 23:05  linxiong1991  阅读(102)  评论(0编辑  收藏  举报

导航