c语言最长公共子序列自顶向下和自底向上代码
时间: 2024-06-18 09:05:36 浏览: 86
C语言中求解最长公共子序列可以使用动态规划算法,其中自顶向下和自底向上是两种不同的实现方式。
自顶向下的代码实现:
```
#include <stdio.h>
#include <string.h>
#define MAXLEN 100
int lcs(char *str1, char *str2, int m, int n, int memo[][MAXLEN]) {
if (m == 0 || n == 0) {
return 0;
}
if (memo[m-1] != -1) {
return memo[m-1][n-1];
}
if (str1[m-1] == str2[n-1]) {
memo[m-1][n-1] = 1 + lcs(str1, str2, m-1, n-1, memo);
} else {
memo[m-1][n-1] = (lcs(str1, str2, m, n-1, memo) > lcs(str1, str2, m-1, n, memo)) ? lcs(str1, str2, m, n-1, memo) : lcs(str1, str2, m-1, n, memo);
}
return memo[m-1][n-1];
}
int main() {
char str1[MAXLEN], str2[MAXLEN];
int m, n;
scanf("%s", str1);
scanf("%s", str2);
m = strlen(str1);
n = strlen(str2);
int memo[MAXLEN][MAXLEN];
memset(memo, -1, sizeof(memo));
printf("The length of the longest common subsequence is %d\n", lcs(str1, str2, m, n, memo));
return 0;
}
```
自底向上的代码实现:
```
#include <stdio.h>
#include <string.h>
#define MAXLEN 100
int lcs(char *str1, char *str2) {
int m = strlen(str1);
int n = strlen(str2);
int memo[MAXLEN][MAXLEN];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
memo[i][j] = 0;
} else if (str1[i-1] == str2[j-1]) {
memo[i][j] = 1 + memo[i-1][j-1];
} else {
memo[i][j] = (memo[i][j-1] > memo[i-1][j]) ? memo[i][j-1] : memo[i-1][j];
}
}
}
return memo[m][n];
}
int main() {
char str1[MAXLEN], str2[MAXLEN];
scanf("%s", str1);
scanf("%s", str2);
printf("The length of the longest common subsequence is %d\n", lcs(str1, str2));
return 0;
}
```
阅读全文