请使用C语言编写用动态规划算法、递归算法求最长公共子序列的代码
时间: 2024-02-27 21:56:10 浏览: 81
动态规划算法:
```c
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
int longest_common_subsequence(char s1[], char s2[]) {
int m = strlen(s1), n = strlen(s2);
int dp[MAXLEN+1][MAXLEN+1];
int i, j;
for (i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for (j = 0; j <= n; j++) {
dp[0][j] = 0;
}
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
if (s1[i-1] == s2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = (dp[i-1][j] > dp[i][j-1]) ? dp[i-1][j] : dp[i][j-1];
}
}
}
return dp[m][n];
}
int main() {
char s1[MAXLEN+1], s2[MAXLEN+1];
scanf("%s %s", s1, s2);
int len = longest_common_subsequence(s1, s2);
printf("%d\n", len);
return 0;
}
```
递归算法:
```c
#include <stdio.h>
#include <string.h>
int longest_common_subsequence(char s1[], char s2[], int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
if (s1[m-1] == s2[n-1]) {
return longest_common_subsequence(s1, s2, m-1, n-1) + 1;
} else {
int len1 = longest_common_subsequence(s1, s2, m-1, n);
int len2 = longest_common_subsequence(s1, s2, m, n-1);
return (len1 > len2) ? len1 : len2;
}
}
int main() {
char s1[MAXLEN+1], s2[MAXLEN+1];
scanf("%s %s", s1, s2);
int len = longest_common_subsequence(s1, s2, strlen(s1), strlen(s2));
printf("%d\n", len);
return 0;
}
```
这里使用了 MAXLEN 宏定义来指定字符串的最大长度,可以根据实际情况修改。
阅读全文