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?

思路

利用DP的方法得出结果,复杂度是O(n^2)。

为什么要用DP?是因为如果我们采取最直接的Backtrack方法,可以看到调用栈(调用树)当中有非常多的重复调用,此时因为这些重复的调用时独立的,因此我们可以采用DP的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public int lengthOfLIS(int[] nums) {
int dp[] = new int[nums.length];
for(int i = 0; i < nums.length; i++){
dp[i] = Math.max(1, dp[i]);
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]){
dp[i] = Math.max(dp[i], dp[j]+1);
}
}
}
int max = 0;
for (int i = 0; i<dp.length; i++){
if(dp[i] > max){
max = dp[i];
}
}
if(nums.length > 0) return max;
else return 0;
}
}

参考资料: http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/