最長上升子序列LIS問題屬於動態規劃的初級問題,用純動態規劃的方法來求解的時間複雜度是O(n^2)。可是若是加上二叉搜索的方法,那麼時間複雜度能夠降到nlog(n)。html
具體分析參考:http://blog.chinaunix.net/uid-26548237-id-3757779.htmlios
代碼:ui
#include <iostream> using namespace std; int LIS_nlogn(int *arr, int len) { int *LIS = new int[len]; //LIS[i]存儲的是每一個最長長度i的最小結尾,即在arr裏的最小結尾 for (int i = 0; i < len; i++) { LIS[i] = -1; } int maxLen = 1; //記錄最長上升子串的最大長度 LIS[0] = arr[0]; for (int i = 0; i < len; ++i) { int low = 0, high = maxLen, mid; while (low <= high) { mid = (low + high)/2; if (LIS[mid] < arr[i]) { low = mid + 1; } else { high = mid - 1; } } LIS[low] = arr[i]; //插入元素到相應的位置 if (low > maxLen) { maxLen++; } } delete LIS; return maxLen; } int main() { int arr[] = {2,1,5,3,6,4,8,9,7}; int len = 9; int ret; ret = LIS_nlogn(arr, len); cout<<ret<<endl; return 0; }