Given an unsorted array of integers, find thelengthof longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore thelengthis4. Note that there may be more than one LIS combination, itis only necessary for you toreturnthelength.
Your algorithm should runin O(n2) complexity.
Follow up: Could you improve itto O(n log n) time complexity?
这道题目比较简单,找出递推公式即可:
dp[i] = max(dp[i],dp[j]+1);
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n,1);
int maxLen = 1;
if(n <= 0){
return0;
}
for(int i = 1;i < n; ++i){
for(int j = 0;j < i; ++j){
if(nums[i] > nums[j]){
dp[i] = max(dp[i],dp[j]+1);
}
}
maxLen = max(maxLen,dp[i]);
}
return maxLen;
}
};