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

leetcode 300 : Longest Increasing Subsequence

2015-11-06 13:16 344 查看
1、原题如下:

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.

2、解题如下:

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

return result;
}
};


3、 总结

本题思路:对于任意前i个数据,它的LIS(i)=1+max{LIS(j)},其中j小于且nums[j]小于nums[i];于是双循环遍历即可。

本题还有nlogn复杂度的方法,后续更新~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++ 面试