Problem Description: Give a sequence a1,a2,a3,a4,a5,a6,a7....an, a subsequence (set to S1,S2,... SN), so that this sub-sequence satisfies the nature, S1<S2<S3<...<SN and the length of the sub-sequence is the longest. Referred to as LIS.
For example, for an array[10, 9, 2, 5, 3, 7, 101, 18],它的最长递增子序列为[2,3,7,101],长度为4。当然最长递增子序列不止一个,例如[2,5,7,101],[2,5,7,18]都符合要求。
1. Complexity of Time: O (n^2)
For sequence A (a1,a2,a3.....an), the increment sequence that is the minimum value of the AM element in the sequence is only related to am-1,am-2,......an, regardless of the element before am, so we can sequentially find the longest increment sequence starting with each element. We use an array of flags to store the length of the longest increment subsequence, if i<j,a[i] < a[j], then flag[i] = max (flag[x], j <= x <= a.length) + 1.
1:publicint lengthoflis (int[] nums) {
2: if (Nums = = NULL | | nums.length = = 0)
3: return 0;
4: int New int [Nums.length];
5: Arrays.fill (flag,1);
6: int maxLength = 1;
7: for (int i =nums.length-2; I >= 0; i--) {
8: int maxtemp = flag[i];
9: for (int j = i+1; J < nums.length;j++) {
Ten: if (Nums[i] < nums[j]) {
One : maxtemp = maxtemp > Flag[j] + 1 maxtemp:flag[j] + 1;
: }
: }
: flag[i] = maxtemp;
: maxLength = maxLength > Flag[i]? maxlength:flag[i];
: }
: return maxLength;
: }
2. Time complexity O (NLOGN)
We define an array dp[],dp[i] to represent the value of the smallest element in a sequence of length I. For example, for sequence a[10, 9, 2, 5, 3, 7, 101, 18],我们依次扫描每个元素,
首先对于A[0] = 10 , 我们可以得dp[1] = 10 ,表示序列长度为1的最小元素为10,此时序列为10,
对于A[1] = 9, 因为A[1] < dp[1],所以dp[1] = 9,此时序列为9
对于A[2] = 2, 因为A[2] < dp[1],所以dp[1] = 2,此时序列为2
对于A[3] = 5, 因为A[3] > dp[1],所以dp[2] = 5,此时序列为2,5
对于A[4] = 3, 因为A[4] < dp[2],所以dp[2] = 3,此时序列为2,3
对于A[5] = 7, 因为A[5] > dp[2],所以dp[3] = 7,此时序列为2,3,7
对于A[6] = 101, 因为A[6] > dp[3],所以dp[3] = 101,此时序列为2,3,7,101
对于A[7] = 18, 因为A[7] < dp[3],所以dp[3] = 18,此时序列为2,5,7,18
所以最长递增子序列的长度为4
1:intnewint[nums.length];
2: int len = 0;
3:
4: for (int x:nums) {
5: int i = Arrays.binarysearch (DP, 0, Len, x);
6: if (I < 0) i =-(i + 1);
7: dp[i] = x;
8: if (i = = len) len++;
9: }
10:
One : return Len;
Two algorithms of longest increasing subsequence