首页 > 其他 > 详细

LeetCode – Refresh – Distinct Subsequences

时间:2015-03-19 08:47:31      阅读:316      评论:0      收藏:0      [点我收藏+]

This DP is a little bit tricky. You need to clear that:

when S[i-1] == T[j-1], it has two part :

1. dp[i-1][j-1], this means from 0 - j-1, it already matches the 0 - i-1. Then last i matches j.

2. dp[i-1][j], from 0 - j already have been matched with 0 - i-1. So whatever i is what, it should be fine.

 

Then here‘s the code:

 1 class Solution {
 2 public:
 3     int numDistinct(string S, string T) {
 4         int l1 = S.size(), l2 = T.size();
 5         vector<vector<int> > dp(l1+1, vector<int> (l2+1, 0));
 6         for (int i = 0; i <= l1; i++) dp[i][0] = 1;
 7         for (int i = 1; i <= l2; i++) dp[0][i] = 0;
 8         for (int i = 1; i <= l1; i++) {
 9             for (int j = 1; j <= l2; j++) {
10                 if (S[i-1] == T[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
11                 else dp[i][j] = dp[i-1][j];
12             }
13         }
14         return dp[l1][l2];
15     }
16 };

 

LeetCode – Refresh – Distinct Subsequences

原文:http://www.cnblogs.com/shuashuashua/p/4349376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!