Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4
public class Solution {
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
public int longestIncreasingSubsequence(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
int[] dp = new int[nums.length];
for (int i = 0; i < dp.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] < nums[j]) {
continue;
}
dp[i] = Math.max(dp[i], dp[j] + 1);
}
max = Math.max(max, dp[i]);
}
return max;
}
}
CORRECT DP:
f[i] denotes the LIS ending with nums[i]. 只有f(i)表示的LIS是以i结束的我们才能枚举所有的j < i,当num[j] <= num[i]的时候,f(i)的值是这些f(j)中的最大值+1. 这两种方式的区别在于,当使用第一种方式是,如果num[j] <= num[i],那么i一定可以从j推出,如果使用第二种方式,就算num[j]<=num[i], 我们仍需要比较num[j]中取的最后一个数是不是小于num[i].
参考:
7 8 9 10 11 12 4 2 4 5 3 7. 第一种方式,f(2) = 1,到3的时候我们看到前面2比3小,所以f(3) = f(2) + 1 = 2.
如果用第二种方式,那么 f(2) = 6, f (3) = 7 就错了。。我们要比较的是当前的num[i]与前面那么多j个lis中最后取的元素的大小关系。
INCORRECT DP:
f[i] denotes the LIS up to i.