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,想了想感觉很难上手,后来看了别人的思路:
(以S="rabbbit"
,T = "rabbit"
为例):
这道题应该很容易感觉到是动态规划的题目。还是老套路,先考虑我们要维护什么量。这里我们维护res[i][j],对应的值是S的前i个字符和T的前j个字符有多少个可行的序列(注意这道题是序列,不是子串,也就是只要字符按照顺序出现即可,不需要连续出现)。下面来看看递推式,假设我们现在拥有之前的历史信息,我们怎么在常量操作时间内得到res[i][j]。假设S的第i个字符和T的第j个字符不相同,那么就意味着res[i][j]的值跟res[i-1][j]是一样的,前面该是多少还是多少,而第i个字符的加入也不会多出来任何可行结果。如果S的第i个字符和T的第j个字符相同,那么所有res[i-1][j-1]中满足的结果都会成为新的满足的序列,当然res[i-1][j]的也仍是可行结果,所以res[i][j]=res[i-1][j-1]+res[i-1][j]。所以综合上面两种情况,递推式应该是res[i][j]=(S[i]==T[j]?res[i-1][j-1]:0)+res[i-1][j]。算法进行两层循环,时间复杂度是O(m*n)代码如下:
一维code如下:
1 public class Solution { 2 public int numDistinct(String S, String T) { 3 if (S==null || T==null || S.length() < T.length()) return 0; 4 int[] res = new int[T.length()+1]; 5 res[0] = 1; 6 for (int i=1; i<=S.length(); i++) { 7 for (int j=T.length(); j>0; j--) { 8 res[j] = S.charAt(i-1) == T.charAt(j-1)? res[j-1] + res[j] : res[j]; 9 } 10 } 11 return res[T.length()]; 12 } 13 }
二维code:
1 public class Solution { 2 public int numDistinct(String S, String T) { 3 if (S==null || T==null || S.length() < T.length()) return 0; 4 int[][] res = new int[S.length()+1][T.length()+1]; 5 for (int m=0; m<=S.length(); m++) { 6 res[m][0] = 1; 7 } 8 for (int i=1; i<=S.length(); i++) { 9 for (int j=1; j<=T.length(); j++) { 10 if (j > i) continue; 11 else if (S.charAt(i-1) == T.charAt(j-1)) { 12 res[i][j] = res[i-1][j-1] + res[i-1][j]; 13 } 14 else { 15 res[i][j] = res[i-1][j]; 16 } 17 } 18 } 19 return res[S.length()][T.length()]; 20 } 21 }