首页 > 代码库 > LeetCode: Distinct Subsequences

LeetCode: Distinct Subsequences

LeetCode: Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit", T = "rabbit"

Return 3.

地址:https://oj.leetcode.com/problems/distinct-subsequences/

算法:这道题的题目描述的不是很清楚。按照题目给出的例子,应该是在S中寻找等于T的子序列,然后求这样的子序列的个数。我是用动态规划解决的,用二维dp来存储子问题的解,其中dp[i][j]表示子问题(T[0~i],S[0~j])的解,这样我们就可以按行优先来完成各个子问题,其中如果T[i]==S[j],那么dp[i][j]=dp[i][j-1] + dp[i-1][j-1];否则,dp[i][j]=dp[i][j-1]。其中第一行跟第一列都可以实现初始化。代码:

 1 class Solution { 2 public: 3     int numDistinct(string S, string T) { 4         if (S.empty() || T.empty()){ 5             return 0; 6         } 7         int len_S = S.size(); 8         int len_T = T.size(); 9         vector<int> temp(len_S);10         vector<vector<int> > dp(len_T,temp);11         if(T[0] == S[0])    dp[0][0] = 1;12         else    dp[0][0] = 0;13         for(int i = 1; i < len_S; ++i){14             if(T[0] == S[i]){15                 dp[0][i] = dp[0][i-1] + 1;16             }else{17                 dp[0][i] = dp[0][i-1];18             }19         }20         for(int i = 1; i < len_T; ++i){21             dp[i][0] = 0;22         }23         for(int i = 1; i < len_T; ++i){24             for(int j = 1; j < len_S; ++j){25                 if(T[i] != S[j]){26                     dp[i][j] = dp[i][j-1];27                 }else{28                     dp[i][j] = dp[i][j-1] + dp[i-1][j-1];29                 }30             }31         }32         return dp[len_T-1][len_S-1];33     }34 };

 

LeetCode: Distinct Subsequences