115. Distinct Subsequences
题目
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
实例
分析
- 可以看出这是一道动态规划的题目,而对于有两个字符串或对象之间的比较问题或者显式的二维问题一般开始步骤都是创建一个二维数组,数组的大小要为参数的长度加1,这是因为初始化的问题。
- 所以这一道题也是一样,创建一个大小为N+1,M+1的数组,其中N是t(字串)的长度,M是s(母串)的长度。
- 因为填表的顺序是从左至右,从上至下,也就是现在s[1:m]中匹配t[1:n]的串的个数,所以就数组的[0][:]赋值为1,而[:][1:]赋值为0
- 填表的时候有以下的规则:
- 当t[i] = s[j]的时候:
- arr[i+1][j+1] = arr[i+1][j] + arr[i][j]
- 反之则 arr[i+1][j+1] = arr[i+1][j]
- 当t[i] = s[j]的时候:
- 最后的返回值是arr[N][M]
题解
class Solution{
public:
// s=>t the num of the ways to generate t
int numDistinct(string s, string t) {
int M = s.length();
int N = t.length();
int total[N+1][M+1];
// means the a, b max
for (int i = 0; i <= N; i++){
total[i][0] = 0;
}
for (int i = 0; i <= M; i++){
total[0][i] = 1;
}
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
total[i+1][j+1] = 0;
if(t[i] == s[j]) total[i+1][j+1] = total[i + 1][j] +total[i][j];
else total[i + 1][ j + 1] = total[i + 1][j];
}
}
return total[N][M];
}
};