Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
1 | Input: [10,9,2,5,3,7,101,18] |
Note:
- 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[nums.length]的数组来表示每个以i位置处的数结尾的递增子序列的最大长度。初始每个位置为1。
例子中的[10,9,2,5,3,7,101,18]对应的初始dp[]就是[1,1,1,1,1,1,1,1],因为加入数组是单调递减的,那么没有任意两个数是递增的,递增的最大单位只有每个数自己本身,这样的情况下每一个数结尾的最长递增子序列的长度都为1.
接着,我们可以比较每一个位置处的nums[i]和它前边的nums[i-1],nums[i-2]…nums[0]的大小关系,只要大于对应的值,我们就比较dp[i]和dp[i-1]+1或dp[i-2]+1或dp[0]+1的大小,取最大的值放入dp[i]。这样计算直到我们遍历完数组中的每一个元素的dp[i]取出其中最大的就是最长递增子序列的长度。
代码如下:
1 | public class LongestIncresing2 { |