Description:
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).
example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
题目思考:
题目给定两个字符串,只可以用删除字符的方法从第一个字符串变换到第二个字符串,求出一共有多少种变换方法;
这是动态规划思想常见应用的典型题目。
Solution:
class Solution {
public:
int numDistinct(string s, string t) {
int len = t.length();
int *memo = new int[len + 1];
for (int i = 0; i < len + 1; i++) {
memo[i] = 0;
}
memo[0] = 1;
for (int i = 1; i < s.length() + 1; i++) {
for (int j = len - 1; j >= 0; j--) {
memo[j + 1] += s[i - 1] == t[j] ? memo[j] : 0;
}
}
return memo[len];
}
};
int main(int argc, const char * argv[]) {
Solution s;
cout << s.numDistinct("rabbbit", "rabbit") << endl;
return 0;
}
public:
int numDistinct(string s, string t) {
int len = t.length();
int *memo = new int[len + 1];
for (int i = 0; i < len + 1; i++) {
memo[i] = 0;
}
memo[0] = 1;
for (int i = 1; i < s.length() + 1; i++) {
for (int j = len - 1; j >= 0; j--) {
memo[j + 1] += s[i - 1] == t[j] ? memo[j] : 0;
}
}
return memo[len];
}
};
int main(int argc, const char * argv[]) {
Solution s;
cout << s.numDistinct("rabbbit", "rabbit") << endl;
return 0;
}