代码随想录算法训练营Day55 | 392.判断子序列,115.不同的子序列

392.判断子序列

文章链接  |  题目链接  |  视频链接

C++解法

class Solution {
public:
    bool isSubsequence(string s, string t) {
        vector> dp(s.size() + 1, vector(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;
    }
};

Python解法

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        dp = [[0] * (len(t)+1) for _ in range(len(s)+1)]
        for i in range(1, len(s)+1):
            for j in range(1, len(t)+1):
                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[-1][-1] == len(s):
            return True
        return False

115.不同的子序列  

文章链接  |  题目链接  |  视频链接

C++解法

class Solution {
public:
    int numDistinct(string s, string t) {
        vector> dp (s.size()+1, vector(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()];
    }
};

Python解法

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        dp = [[0] * (len(t)+1) for _ in range(len(s)+1)]
        for i in range(len(s)):
            dp[i][0] = 1
        for j in range(1, len(t)):
            dp[0][j] = 0
        for i in range(1, len(s)+1):
            for j in range(1, len(t)+1):
                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[-1][-1]

你可能感兴趣的:(代码随想录刷题训练营,算法)