Question
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up
Could you improve it to O(n log n) time complexity?
Java Code
/**
* 动态规划问题:
* 求数组的最长增量子序列(LIS)的长度
* 解题思路:
* 寻找状态转移关系,发现数组nums在位置i处的LIS依赖于之前每个位置j处的LIS,
* 当nums[i]的值大于nums[j]时,j处的LIS可以继续增长,
* 再比较每一个j处LIS增长之后的长度,取最大长度作为当前位置i处的LIS
*
* @author 漫游者
*/
public int lengthOfLIS(int[] nums) {
//用于储存nums数组中每个元素处的LIS长度
int[] lis = new int[nums.length];
int maxLength = 0;
for(int i = 0; i < nums.length; ++i) {
//当前元素处的LIS长度至少为1
lis[i] = 1;
for(int j = 0; j<i; ++j) {
//如果在当前位置i之前有更小的元素,且其LIS长度不小于当前的LIS长度,则更新
if(nums[j] < nums[i] && lis[j] >= lis[i])
lis[i] = lis[j] + 1;
}
//每次更新maxLength
if(lis[i] > maxLength)
maxLength = lis[i];
}
return maxLength;
}