判断子序列
过程:

- public class Solution {
- public bool IsSubsequence(string s, string t) {
- int[,] dp = new int[s.Length + 1, t.Length + 1];
- for (int i = 1; i <= s.Length; i++) {
- for (int j = 1; j <= t.Length; j++) {
- if (s[i - 1] == t[j - 1]) dp[i, j] = dp[i - 1, j - 1] + 1;
- else dp[i, j] = dp[i, j - 1];
- }
- }
- if (dp[s.Length, t.Length] == s.Length) return true;
- return false;
- }
- }
不同的子序列
这里递推公式中,有相等和不相等两种情况,相等字符是dp[i,j] = dp[i-1,j-1]+dp[i-1,j],例如下图的s和t字符串,循环到最后一个c时,dp[i-1,j-1]是首次遇到的次数,dp[i-1,j]是在此的循环之前所累计的次数,两个相加就是循环到最后一个c时所有的累计结果。如果不相等,就不需要考虑dp[i-1,j-1]

- public class Solution {
- public int NumDistinct(string s, string t) {
- int[,] dp = new int[s.Length+1,t.Length+1];
- for(int i=0;i<=s.Length;i++)dp[i,0] = 1;
- for(int j=1;j<=t.Length;j++)dp[0,j] = 0;
-
- for(int i=1;i<=s.Length;i++){
- for(int j=1;j<=t.Length;j++){
- if(s[i-1] == t[j-1]){
- dp[i,j] = dp[i-1,j-1]+dp[i-1,j];
- }else{
- dp[i,j] = dp[i-1,j];
- }
- }
- }
- return dp[s.Length,t.Length];
- }
- }