C language to achieve the longest increasing subsequence problem solution

  • 2020-04-02 02:45:14
  • OfStack

This paper illustrates the solution to the problem of longest increasing subsequence in C language. Share with you for your reference. Specific methods are as follows:

Problem description:

Given a sequence, find its longest increasing subsequence length.

So let's say 1, 3, 7, 5

The output of 3

Algorithm solution:

With the idea of dynamic programming, the maximum length of the subsequence of each point as the rightmost end of the sequence is found, that is, the solution of the problem. Therefore, when calculating each point in front, save the result, and compare the value of the later point with that of the previous point. If the value is large, add 1 to its length, and find out the length of the longest point stored as the current point in all possible situations. Form a recursion.

The specific implementation code is as follows:


#include "stdio.h"
#include "stdlib.h"
#define MAXDATA 10000
int main(){
  int data[MAXDATA]; 
  int lgs[MAXDATA];  
  int n,temp,k; 
  scanf("%d",&n);
  if(n>10000){
     return 0;      
  }
  for(int i=0;i<n;i++){
    scanf("%d",&data[i]);
  }
  for(int i=0;i<MAXDATA;i++){
    lgs[i]=1;  
  }
  for(int i=1;i<n;i++){
    temp=1;
    for(int j=0;j<i;j++){ 
      if(data[i]>data[j]){ 
        if(lgs[i]+lgs[j]>temp){ 
          temp=lgs[i]+lgs[j];
        } 
      }
    }
    lgs[i]=temp;
  }
  temp=lgs[0];
  for(int i=1;i<n;i++){
    if(lgs[i]>temp){
      temp=lgs[i];
    }
  }
  printf("%d",temp);
  system("pause");
}

I hope that this paper is helpful to the learning of C programming algorithm design.


Related articles: