动态规划
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
vector<int> dp(n,0);
int res = 0;
for(int i = 0; i < n; i++){
dp[i] = 1;
for(int j = 0; j < i; j++){
if(nums[i] > nums[j]){
dp[i] = max(dp[i],dp[j] + 1);
}
}
res = max(res, dp[i]);
}
return res;
}
};
二分法
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
//开一个数组,用于维护一个递增的序列,通过二分查找找到当前元素在该数组中的插入位置,插入元素。
int n = nums.size();
if(n == 0) return 0;
vector<int> dp;
int k = 0;
for(int i = 0; i < n; i++){
int l = 0, r = k;
while(l < r){
int mid = l + (r-l)/2;
if(dp[mid] < nums[i]){
l = mid+1;
}else{
r = mid;
}
}
if(r == k){
dp.push_back(nums[i]);
k++;
}else{
dp[r] = nums[i];
}
}
return dp.size();
}
};