LeetCode: Distinct Subsequences

一开始dfs没过large, 网上看了别人的dp,哎,这题比较难。。

 1 class Solution {

 2 public:

 3     int numDistinct(string S, string T) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         vector<vector<int>> f(S.size()+1, vector<int>(T.size()+1));

 7         for (int i = 0; i <= S.size(); i++) f[i][0] = 0;

 8         for (int i = 0; i <= T.size(); i++) f[0][i] = 0;

 9         for (int i = 1; i <= S.size(); i++) {

10             if (S[i-1] == T[0]) f[i][1] = f[i-1][1]+1;

11             else f[i][1] = f[i-1][1];

12         }

13         for (int i = 2; i <= S.size(); i++) {

14             for (int j = 2; j <= T.size(); j++) {

15                 if (S[i-1] == T[j-1]) f[i][j] = f[i-1][j-1]+f[i-1][j];

16                 else f[i][j] = f[i-1][j];

17             }

18         }

19         return f[S.size()][T.size()];

20     }

21 };

 c#

 1 public class Solution {

 2     public int NumDistinct(string s, string t) {

 3         int[,] f = new int[s.Length+1, t.Length+1];

 4         for (int i = 1; i <= s.Length; i++) {

 5             if (s[i-1] == t[0]) f[i, 1] = f[i-1, 1] + 1;

 6             else f[i, 1] = f[i-1, 1];

 7         }

 8         for (int i = 2; i <= s.Length; i++) {

 9             for (int j = 2; j <= t.Length; j++) {

10                 if (s[i-1] == t[j-1]) f[i, j] = f[i-1, j-1] + f[i-1, j];

11                 else f[i, j] = f[i-1, j];

12             }

13         }

14         return f[s.Length, t.Length];

15     }

16 }
View Code

 

你可能感兴趣的:(LeetCode)