The second question is not too difficult. I did it for an hour, and finally found that the key is nothing more than finding the meaning of dp. After confirming it, look for the relationship between the previous stage and the next stage, and finally determine the traversal order.
Question 1: 392. Judgment subsequence - LeetCode
Given strings s and t , determine whether s is a subsequence of t .
A subsequence of a string is a new string formed by deleting some (or not) characters from the original string without changing the relative positions of the remaining characters. (eg, "ace"
is "abcde"
a subsequence of , and "aec"
is not).
Idea: This question does not require continuity, so some nodes need to be deleted during the matching process. dp[i][j] indicates the number of s appearing in the i-th element of t. If the length of the final dp is equal to the length of T, it is expressed as subsequence. code show as below:
class Solution {
public:
bool isSubsequence(string s, string t) {
vector<vector<int>> dp(s.size()+1,vector<int>(t.size()+1,0));
for(int i = 1; i <= s.size(); i++){
for(int j = 1; j <= t.size(); 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.size()][t.size()] == s.size()) return true;
return false;
}
};
Problem 2: 115. Different subsequences - LeetCode
Given two strings s
and t
, count and return the number of occurrences in the subsequence ofs
. t
The question data guarantees that the answer fits within the range of a 32-bit signed integer.
Idea: dp[i][j] represents the number of times the substring ending with j-1 in t appears in the substring ending with i-1 in s, and then draw the matrix to get the recurrence relationship of dp, the code as follows:
class Solution {
public:
int numDistinct(string s, string t) {
vector<vector<uint64_t>> dp(s.size() + 1, vector<uint64_t>(t.size() + 1));
for (int i = 0; i < s.size(); i++) dp[i][0] = 1;
for (int j = 1; j < t.size(); j++) dp[0][j] = 0;
for (int i = 1; i <= s.size(); i++) {
for (int j = 1; j <= t.size(); 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.size()][t.size()];
}
};