单调递增最长子序列
时间限制:3000 ms | 内存限制:65535 KB
难度:4
-
描述
- 求一个字符串的最长递增子序列的长度
如:dabdbf最长递增子序列就是abdf,长度为4-
输入
- 第一行一个整数0<n<20,表示有n个字符串要处理
随后的n行,每行有一个字符串,该字符串的长度不会超过10000
输出 - 输出字符串的最长递增子序列的长度 样例输入
-
3 aaa ababc abklmncdefg
样例输出 -
1 3 7
- 第一行一个整数0<n<20,表示有n个字符串要处理
很经典的题目 参考的 http://blog.youkuaiyun.com/sjf0115/article/details/8715672
用动态规划做的 时间复杂度n²
讲的很棒 一开始没有理解aj < ai && j < i这个限制条件 于是写出了这个代码
#include<stdio.h>
#include<string.h>
int main() {
char s[10005];
int n, len, dp[10005];
scanf("%d", &n);
while(n--) {
int max = 0;
scanf("%s", s);
len = strlen(s);
for(int i = 0; i < len; i++) {
dp[i] = 1;
for(int j = 0; j < i; j++)
if(s[i] > s[j])
dp[i] = dp[j]+1;
printf("遍历第%d次结果:", i+1);
for(int i = 0; i < strlen(s); i++)
printf("%d ", dp[i]);
printf("\n");
}
for(int i = 0; i < len; i++)
if(dp[i] > max)
max = dp[i];
printf("%d\n", max);
}
}
再遍历中发现了错误
测试了 一组数据 abcdabetawe
a b c d a b e t a w e
遍历第1次结果:1 0 0 0 0 0 0 0 0 0 0
遍历第2次结果:1 2 0 0 0 0 0 0 0 0 0
遍历第3次结果:1 2 3 0 0 0 0 0 0 0 0
遍历第4次结果:1 2 3 4 0 0 0 0 0 0 0
遍历第5次结果:1 2 3 4 1 0 0 0 0 0 0
遍历第6次结果:1 2 3 4 1 2 0 0 0 0 0
遍历第7次结果:1 2 3 4 1 2 3 0 0 0 0
遍历第8次结果:1 2 3 4 1 2 3 4 0 0 0
遍历第9次结果:1 2 3 4 1 2 3 4 1 0 0
遍历第10次结果:1 2 3 4 1 2 3 4 1 2 0
遍历第11次结果:1 2 3 4 1 2 3 4 1 2 2
更新大小时应该考虑dp[i] 和 1+dp[j]之间的大小关系
正确的遍历结果应该是
a b c d a b e t a w e
遍历第1次结果:1 0 0 0 0 0 0 0 0 0 0
遍历第2次结果:1 2 0 0 0 0 0 0 0 0 0
遍历第3次结果:1 2 3 0 0 0 0 0 0 0 0
遍历第4次结果:1 2 3 4 0 0 0 0 0 0 0
遍历第5次结果:1 2 3 4 1 0 0 0 0 0 0
遍历第6次结果:1 2 3 4 1 2 0 0 0 0 0
遍历第7次结果:1 2 3 4 1 2 5 0 0 0 0
遍历第8次结果:1 2 3 4 1 2 5 6 0 0 0
遍历第9次结果:1 2 3 4 1 2 5 6 1 0 0
遍历第10次结果:1 2 3 4 1 2 5 6 1 7 0
遍历第11次结果:1 2 3 4 1 2 5 6 1 7 5
7
贴出最终AC代码
#include<stdio.h>
#include<string.h>
int main() {
char s[10005];
int n, len, dp[10005];
scanf("%d", &n);
while(n--) {
int max = 0;
scanf("%s", s);
len = strlen(s);
for(int i = 0; i < len; i++) {
dp[i] = 1;
for(int j = 0; j < i; j++)
if(s[i] > s[j] && dp[i] < 1+dp[j])
dp[i] = dp[j]+1;
/*
这里if也可以写成
if(a[i] > a[j]) dp[i] = max(dp[i], dp[j]+1);
*/
}
for(int i = 0; i < len; i++)
if(dp[i] > max)
max = dp[i];
printf("%d\n", max);
}
}