Description:
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.
简要题解:
采用动态规划。
子问题c(i)为从序列的第0个元素开始,到第i个元素的子序列。
每个子问题c(i)维护两个值: 当前最长递增子序列的长度(记为first); 包含元素i的最长递增序列的长度(记为second)。
第一个子问题的这两个值分别为: 1, 1。
c(i)与c(i-1)的关系是: 如果元素i大于元素i-1,则c(i).first = c(i-1).first + 1, c(i).second = c(i-1).second + 1;否则,c(i).second = max(c(j).second + 1),其中0 <= j < i且元素j小于元素i,没有这样的元素j时,c(i).second = 1,同时,c(i).first = max(c(i).second, c(i-1).first)。
代码:
#include<utility>
using namespace std;
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0)
return 0;
vector<pair<int, int> > LIS(nums.size());
LIS[0].first = 1;
LIS[0].second = 1;
for (int i = 1; i < LIS.size(); i++) {
LIS[i].second = 1;
for (int j = i - 1; j >= 0; j--)
if (nums[i] > nums[j])
LIS[i].second = (LIS[j].second + 1 > LIS[i].second) ? LIS[j].second + 1 : LIS[i].second;
LIS[i].first = (LIS[i].second > LIS[i-1].first) ? LIS[i].second : LIS[i-1].first;
}
return LIS[LIS.size()-1].first;
}
};