【DP】 Record the longest increasing subsequence
原创
©著作权归作者所有:来自51CTO博客作者Lyndon_梁飞的原创作品,请联系作者获取转载授权,否则将追究法律责任
In my last paper if it was called, I just work out the length of the longest increasing subsequnce.But it's not enough to reach the goal.
In order to solve the problem by Dynamic Programming, I just modified the code I wrote last time.
Code as follows
#include <stdio.h>
int main()
{
int num[] = {1, 3, 4, 5, 2, 6, 4, 9};
int* L;
int** pre; /*store the LIS*/
int i, j;
int longest = 0;
int longest_index = 0;
int k = 0;
int num_len = sizeof(num) / sizeof(int);
pre = (int**)malloc(num_len);
for (i = 0; i < num_len; i++)
{
pre[i] = (int*)malloc(num_len);
}
system("cls");
L = (int*)malloc(num_len);
for (i = 0; i < num_len; i++)
{
L[i] = 1;
for (j = 0; j < i; j++)
{
if (num[j] < num[i] && L[i] <= L[j] + 1)
{
L[i] = L[j] + 1;
pre[i][k++] = num[j];
if (L[i] > longest)
{
longest = L[i];
longest_index = i;
}
}
}
pre[i][k] = num[i];
k = 0;
}
for (i = 0; i <longest; i++)
{
printf("%d ", pre[longest_index][i]);
}
getchar();
return 0;
}