Java for LeetCode 115 Distinct Subsequences【HARD】
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问题,弄清递推公式即可,参考Distinct Subsequences@LeetCode ,JAVA实现如下:
public int numDistinct(String s, String t) { if (t.length() == 0) return 1; int[] dp = new int[t.length() + 1]; dp[0] = 1; for (int i = 0; i < s.length(); i++) { int last = 1; for (int j = 0; j < t.length(); j++) { if (dp[j] == 0) break; int temp = dp[j + 1]; if (s.charAt(i) == t.charAt(j)) dp[j + 1] += last; last = temp; } } return dp[t.length()]; }