码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Distinct Subsequences

时间:2015-03-19 08:50:24      阅读:147      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!