leetcode-distinct sequences

本文介绍了一种使用动态规划解决两个字符串匹配问题的方法,通过计算目标字符串T在源字符串S中出现的不同子序列次数,实现了高效求解。文章详细解释了动态规划状态转移方程,并给出了具体实现代码。
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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值