您的位置:首页 > 产品设计 > UI/UE

Longest Increasing Subsequence

2016-06-22 16:29 441 查看
题目描述:

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]要么等于dp[i-1],要么等于dp[i-1]+1.这样讨论起来就比较复杂了。

这个题的递归式是:dp[i] = max{dp[j] + 1,dp[i]}     其中j < i && nums[j] < nums[i]

然后用自下而上的动态规划算法即可求解:

public class Solution {
public int lengthOfLIS(int[] nums) {
if(nums.length<2)
return nums.length;
int[] dp=new int[nums.length];
Arrays.fill(dp, 1);int max=1;
for(int i=1;i<nums.length;i++){
for(int j=0;j<i;j++){
if(nums[j]<nums[i]&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
if(dp[i]>max)
max=dp[i];
}
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: