LeetCode Distinct Subsequences

来源:互联网 发布:通风管道阻力计算软件 编辑:程序博客网 时间:2024/06/04 01:29

Description:

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.

Solution:

Assume dp[i][j] represents the number of distinct subsequences from s[1,i] to t[1,j] 

Like the edit distance, we should start from empty string(dp[0][i] and dp[i][0])

And it is very simple to come to the idea that

dp[i][0] = 1 s.t. any i

dp[0][i] = 0 s.t. i>=1

Then start the loop

If s[i] != t[j]: dp[i][j] = dp[i-1][j]   (1)

Else: dp[i][j] = dp[i-1][j] + dp[i-1][j-1]   (2)

(1) s[i] and t[j] does not equal, then the distinct number is equal to dp[i-1][j]

(2) since these two are equal, we can utilize this in two ways: match s[i] and t[j], then we can get dp[i-1][j-1]; do not match s[i] and t[j], then we can get dp[i-1][j]. So for this condition, dp[i][j] = dp[i-1][j-1] + dp[i-1][j].

<span style="font-size:18px;">public class Solution {public int numDistinct(String s, String t) {int n = s.length();int m = t.length();int dp[][] = new int[n + 1][m + 1];for (int i = 0; i <= n; i++)dp[i][0] = 1;for (int j = 1; j <= m; j++)dp[0][j] = 0;char ch1, ch2;for (int i = 1; i <= n; i++) {ch1 = s.charAt(i - 1);for (int j = 1; j <= m; j++) {ch2 = t.charAt(j - 1);if (ch1 != ch2)dp[i][j] = dp[i - 1][j];else {dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];}}}return dp[n][m];}}</span>


0 0
原创粉丝点击