代码随想录算法训练营第57天|392.判断子序列、115.不同的子序列

392.判断子序列

https://leetcode.cn/problems/is-subsequence/

class Solution {
public:
    bool isSubsequence(string s, string t) {
        vector> dp(s.length() + 1, vector(t.length() + 1, false));
        for (int j = 0; j <= t.length(); j++) {
            dp[0][j] = true;
        }
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s[i - 1] == t[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                }
                else {
                    dp[i][j] = dp[i][j - 1];
                }
            }
        }
        return dp.back().back();
    }
};

115.不同的子序列

https://leetcode.cn/problems/distinct-subsequences/

class Solution {
public:
    int numDistinct(string s, string t) {
        vector> dp(s.length() + 1, vector(t.length() + 1, 0));
        for (int i = 0; i <= s.length(); i++) {
            dp[i][0] = 1;
        }
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); 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.back().back();
    }
};

ps:leetcode有误 

 

你可能感兴趣的:(算法,leetcode,动态规划)