leetcode-distinct sequences

Solution: when see question about two strings , DP should be considered first.
We can abstract this question to calculate appear times for string T with length i in string S with length j, which can be represented by numbers[i][j], then through observation and thinking , we can know for numbers[i][j] it should at least equal the numbers[i][j-1] and if T.charAt(i)==S.charAt(j) , numbers[i][j] should also be add numbers[i-1][j-1]
 
 1 class Solution
 2 {
 3 public:
 4     int numDistinct(string S, string T) {
 5         int sLen = S.length(); int tLen = T.length();
 6         vector<vector<int>> dp(sLen+1,vector<int>(tLen+1));//dp[i][j]表示对应S前i个和T前j个字符的子问题。
 7         for (int i = 0; i <= sLen; i++) dp[i][0] = 1;
 8         for (int i = 1; i <= sLen; i++)
 9         {
10             for (int j = 1; j <= tLen; j++)
11             {
12                 if (S[i - 1] == T[j - 1])
13                 {
14                     dp[i][j] = dp[i - 1][j] + dp[i-1][j-1];
15                 }
16                 else
17                 {
18                     dp[i][j] = dp[i-1][j];
19                 }
20             }
21         }
22         return dp[sLen][tLen];
23     }
24 
25 };
26 int main()
27 {
28     Solution s;
29     string strS("b");
30     string strT("a");
31     cout << s.numDistinct(strS, strT) << endl;
32     return 0;
33 }

 

 http://rleetcode.blogspot.com/2014/01/distinct-subsequences-java.html

转载于:https://www.cnblogs.com/forcheryl/p/4051215.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值