最长递增子序列——解题报告

来源:互联网 发布:oracle数据库nvl函数 编辑:程序博客网 时间:2024/06/04 12:55

最长递增子序列——解题报告

    

    题目描述:给定一个数组,长度为n,求出其中最长递增子序列。


    分析:这题可以用动态规划求解,遍历i = 1 : n,当第i个数比前面j数大,而且前面的子序列长度加1之后,比现在的第i个子序列长的话,那么就变换。额,晦涩难懂额。。看代码可以好一些。

    代码如下:

#include<iostream>using namespace std; // solution 1: dpint maxSubLength(int a[], int n){int *LIS = new int[n]; int maxLIS = INT_MIN; for(int i = 0; i < n; i++)  // 遍历i{LIS[i] = 1; for(int j = 1; j < i; j++)  // 遍历j,范围是1~i{if(a[j] < a[i] && LIS[j] + 1 > LIS[i])  // 核心部分LIS[i] = LIS[j] + 1; maxLIS = maxLIS > LIS[i] ? maxLIS : LIS[i]; }}return maxLIS; }int main(){int a[] = {1, -1, 2, -3, 4, -5, 6, -7}; // dp algorithmcout<<maxSubLength(a, 8)<<endl; return 0; }



1 0