[Leetcode] Distinct Subsequences (Java)

来源:互联网 发布:express mysql 编辑:程序博客网 时间:2024/05/02 19:13

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.

DP,num[i][j] 保存S(0,i)包含的T(0,j)的数量

S.charAt(i)==T.charAt(j) 时,num[i][j]=num[i-1][j-1]+num[i-1][j];

S.charAt(i)!=T.charAt(j) 时,num[i][j]=num[i-1][j]。

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


0 0