Leetcode: 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.

肯定得用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 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值