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

300. Longest Increasing Subsequence

2016-04-22 00:03 330 查看
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?

Credits:

Special thanks to @pbrother for adding this problem and creating all test cases.

最长上升子序列,N^2的算法,比较简单,简单的动态规划思想。

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len=nums.size();
if(len==0)return 0;
vector<int>f(len);
int maxx=1;
for(int i=0;i<len;i++)
f[i]=1;
for(int i=1;i<len;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j]&&f[j]+1>f[i]){
f[i]=f[j]+1;
}
maxx=max(maxx,f[i]);
}
}
return maxx;
}
};


不过nlogn的算法,之前还真不知道,今天查了下大神的代码,学习了!

主要思路就是用一个数组记录长度len为1~i的递增序列的最后一个元素的值。

查找的时候利用二分的思路。

/article/9565797.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: