原题网址:https://leetcode.com/problems/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
.
方法一:递归+记忆化搜索,但会内存溢出。
public class Solution {
boolean[][] visit;
int[][] nums;
public int numDistinct(String s, String t) {
if (visit == null) {
visit = new boolean[s.length() + 1][t.length() + 1];
nums = new int[s.length() + 1][t.length() + 1];
}
if (visit[s.length()][t.length()]) return nums[s.length()][t.length()];
if (t.length() == 0) return 1;
if (s.length() < t.length()) return 0;
if (s.charAt(s.length() - 1) == t.charAt(t.length() - 1)) {
nums[s.length()][t.length()] = numDistinct(s.substring(0, s.length() - 1), t.substring(0, t.length() - 1));
}
nums[s.length()][t.length()] += numDistinct(s.substring(0, s.length() - 1), t);
visit[s.length()][t.length()] = true;
return nums[s.length()][t.length()];
}
}
方法二:动态规划。
public class Solution {
public int numDistinct(String s, String t) {
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
if (sa.length == 0 || ta.length == 0) return 0;
int[][] nums = new int[ta.length+1][sa.length+1];
for(int j=0; j<=sa.length; j++) nums[0][j] = 1;
for(int i=1; i<=ta.length; i++) {
for(int j=1; j<=sa.length; j++) {
nums[i][j] = nums[i][j-1];
if (sa[j-1] == ta[i-1]) nums[i][j] += nums[i-1][j-1];
}
}
return nums[ta.length][sa.length];
}
}
方法三:动态规划,优化内存。
public class Solution {
public int numDistinct(String s, String t) {
if (t.length() == 0) return 1;
if (s.length() < t.length()) return 0;
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
int[] nums = new int[ta.length + 1];
nums[0] = 1;
for(int i = 1; i <= sa.length; i++) {
int[] next = new int[ta.length + 1];
next[0] = 1;
for(int j = 1; j <= ta.length; j++) {
next[j] = nums[j];
if (sa[i - 1] == ta[j - 1]) {
next[j] += nums[j - 1];
}
}
nums = next;
}
return nums[ta.length];
}
}