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

LeetCode OJ:Longest Increasing Subsequence(最长递增序列)

2015-11-17 20:51 357 查看
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解决,注意这里的递增序列不是指连续的递增 ,可以是不连续的, 代码如下:

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