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
The longest increasing subsequence is
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;
}
}
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;
}
}
相关文章推荐
- easyUI 获取Json 嵌套数据
- SOAPUI压力测试的参数配置
- EasyUI----DataGrid行明细增删改操作
- 有关UICollectionviewController的一些问题
- clEnqueueNDRangeKernel()的各参数意义以及相关注意事项
- 使用UEditor编辑器遇到的问题(java)
- hibernate 的createSQLQuery的几种用法(转)
- input 标签里 value值从数据库读取出来的值显示一半或者没显示原因
- 在seajs中使用require加载静态文件的问题
- 点9图片无效问题以及gradle插件版本与gradle版本和buildtools的对应关系
- 95.UICollectionView添加headerView(类似UITableView的tableHeaderView)
- hbuilder在android手机里用chrome调试,只显示了设备名称,却没有inspect按钮
- UIBezierPath
- 【IOS】This certificate has an invalid issuer问题
- Cloudera:Hue监控页面的时间显示问题
- ActiveMQ学习笔记(上)
- 指定FPS帧频,requestAnimationFrame播放动画
- 2.3、Android Studio使用Layout Editor设计UI
- 94.Build Setting 之 Code Signing 详解
- 2.3、Android Studio使用Layout Editor设计UI