Distinct Subsequences

来源:互联网 发布:淮南南乡子大数据 编辑:程序博客网 时间:2024/06/07 18:42

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.

这道题目主要要注意的 是 initialize的过程,对于所有的 num[ i ][ 0 ] 都要付值为1

 num[ i ][ j ] 表示s 的前i 个数中对于 t 的前j 个数,有多少distinct sequences

public class Solution {    public int numDistinct(String S, String T) {        if (S == null || T == null) {            return 0;        }        int l1 = S.length();        int l2 = T.length();        int[][] num = new int[l1 + 1][l2 + 1];        for (int i = 0; i < l1; i++) {            num[i][0] = 1;        }        for (int i = 0; i < l1; i++) {            for (int j = 0; j < l2; j++) {                if (j > i) {                    break;                }                num[i + 1][j + 1] = S.charAt(i) == T.charAt(j) ? (num[i][j] + num[i ][j + 1]) : num[i][j+1];            }        }        return num[l1][l2];    }}


0 0