https://leetcode-cn.com/problems/distinct-subsequences/
思路:
动态规划思路
d[i][j] 代表 s[0,i-1]与t[0, j-1]中匹配最多的子序列个数
相当于原来问题的子问题
特殊情况是t为空匹配s[0, n-1]的结果都为1,然后进行状态转移递推
注意的当相等的情况分为进行匹配和不进行匹配两种情况分别对应状态d[i-1][j-1]与d[i-1][j]
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
class Solution {
public:
int numDistinct(string s, string t) {
int n = s.length();
int m = t.length();
if(n < m) return 0;
vector<vector<long long> > d(n + 1, vector<long long> (m+1, 0));
for(int i = 0; i <= n; i++) {
d[i][0] = 1;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(s[i-1] == t[j-1]) d[i][j] = d[i-1][j-1] + d[i-1][j];
else d[i][j] = d[i-1][j];
}
}
// for(int i = 1; i <=n; i++) {
// for(int j = 1; j <= m; j++) {
// cout << d[i][j] << " ";
// }
// cout <<endl;
// }
return d[n][m];
}
};
本文介绍了一种使用动态规划解决字符串子序列匹配问题的方法。通过构建二维动态规划表d[i][j]来记录字符串s[0,i-1]与t[0,j-1]中匹配最多的子序列个数。特别地,当两个字符相等时,考虑匹配和跳过两种情况,以实现高效的状态转移。
465

被折叠的 条评论
为什么被折叠?



