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

392. 判断子序列

bool isSubsequence(char * s, char * t){
    int len1 = strlen(s);
    int len2 = strlen(t);
    int dp[len1 + 1][len2 + 1];
    for (int i = 0; i <= len1; i++){
        for (int j = 0; j <= len2; j++){
            dp[i][j] = 0;
        }
    }
    for (int i = 1; i <= len1; i++){
        for (int j = 1; j <= len2; 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[len1][len2] == len1) return true;
    return false;
}

115. 不同的子序列

int numDistinct(char * s, char * t){
    int len1 = strlen(s);
    int len2 = strlen(t);
    unsigned long dp[len1 + 1][len2 + 1];
    for (int i = 0; i <= len1; i++){
        dp[i][0] = 1;
    }

    for (int j = 1; j <= len2; j++){
        dp[0][j] = 0;
    }
    for (int i = 1; i <= len1; i++){
        for (int j = 1; j <= len2; 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[len1][len2];
}

你可能感兴趣的:(代码随想录算法,算法,leetcode,c语言,动态规划)