如题,例如:存在数组 1,-1,2,-3,4,-5,6,-7 ,则最长的递增子序列是:1,2,4,6.
法一:
蛮力法
- int Lis(int* arr,int n)
- {
- int iCount=0;//记录子序列的个数
- int tmp_count=0;
- int tmp;
- for(int i=0;i<n-1;i++)
- {
- tmp=arr[i];
- for(int j=i+1;j<n-1;j++)
- {
- if(arr[j]>tmp)
- {
- iCount++;
- tmp=arr[j];
- }
- }
- if(iCount>tmp_count)
- {
- tmp_count=iCount;
- }
- iCount=0;
- }
- return tmp_count+1;
- }
复杂度为O(N^2);
利用DP来做,最有问题,一般都用dp来做,关键是找到递归公式。
用LIS[i]记录位置i处,最长的递增子序列,编程之美上的解法,真心看不懂,记录下来,以后再看:
- int LIS(int[] array)
- {
- int[] LIS=new int[array.Length];
- for (int i = 0; i < array.Length; i++)
- {
- LIS[i] = 1;
- for (int j = 0; j < i; j++)
- {
- if (array[i] > array[j] && LIS[j] + 1 > LIS[i])
- LIS[i] = LIS[j] + 1;
- }
- }
- }
- return Max(LIS);
- }