标签:
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