典型的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 int m = S.length(); 7 int n = T.length(); 8 return getDistinct(S, T, m - 1, n - 1); 9 } 10 int getDistinct(string &S, string &T, int i, int j) { 11 if (j < 0) { 12 return 1; 13 } 14 if (i < 0) { 15 return 0; 16 } 17 if (j > i) { 18 return 0; 19 } 20 if (S[i] == T[j]) { 21 return (getDistinct(S, T, i - 1, j - 1) + getDistinct(S, T, i - 1, j)); 22 } 23 return getDistinct(S, T, i - 1, j); 24 } 25 };
哎,看来做DP的题目的第一选择就应该是直接用数组保存最优解。
1 class Solution { 2 public: 3 int numDistinct(string S, string T) { 4 int N = S.size(), M = T.size(); 5 int dp[M+1][N+1]; 6 dp[0][0] = 1; 7 for (int j = 1; j <= N; ++j) 8 dp[0][j] = 1; 9 for (int i = 1; i <= M; ++i) 10 dp[i][0] = 0; 11 12 for (int i = 1; i <= M; ++i) 13 for (int j = 1; j <= N; ++j) 14 if (S[j-1] == T[i-1]) 15 dp[i][j] = dp[i][j-1] + dp[i-1][j-1]; 16 else 17 dp[i][j] = dp[i][j-1]; 18 19 return dp[M][N]; 20 } 21 };