题目描述
给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,”ACE” 是 “ABCDE” 的一个子序列,而 “AEC” 不是)题目数据保证答案符合 32 位带符号整数范围
链接:https://leetcode-cn.com/problems/distinct-subsequences

解题思路
dp[i][j]表示在s[:i]中,t[:j]的个数,那么现在有两种情况:
- s[i]==t[j],那么可以用s[i]抵消t[j],此时依赖于dp[i-1][j-1],也可以不采用s[i]抵消t[j],则依赖于dp[i-1][j],故此时:dp[i][j]=dp[i-1][j]+dp[i-1][j-1]
- s[i]!=t[j],则有:dp[i][j]=dp[i-1][j]
同时我们要注意初始化,当j==0时为空字符串,空字符串是任意字符的子串,那么有dp[i][0]=1
class Solution {public:int numDistinct(string s, string t) {int len_s=s.length();int len_tt=t.length();if (len_s < len_tt)return 0;vector<vector<unsigned int>> dp(len_s+1, vector<unsigned int>(len_tt+1, 0));for (int i=0; i<=len_s; i++)dp[i][0]=1;for (int i=1; i<=len_s; i++) {for (int j=1; j<=len_tt; j++) {if (s[i-1]==t[j-1])dp[i][j] += dp[i-1][j-1] + dp[i-1][j];elsedp[i][j] = dp[i-1][j];}}return dp[len_s][len_tt];}};
