Longest Increasing Subsequence
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[i]表示以字符nums[i]结尾的最长子串的长度,那么状态转移方程就是:
dp[i]=Math.max(dp[i],dp[j]+1);0<=j<i;
且nums[j]必须小于nums[i]
另外还需维护一个最大长度。
2.代码
public class Solution {
public int lengthOfLIS(int[] nums) {
if(nums.length==0) return 0;
int[] dp=new int[nums.length];
int maxLength=0;
for(int i=0;i<nums.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[j]<nums[i]){
dp[i]=Math.max(dp[i],dp[j]+1);
}
}
maxLength=Math.max(maxLength,dp[i]);
}
return maxLength;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。