最长上升子序列
最长上升子序列
问题描述
给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence
思路
建立一个tmp数组,作为到tmp[i]时上升子序列的长度,最开始将tmp初始化为1。
因为nums[0]之前没有比它更小的数,所以tmp[i]不做任何改变,为初始值1;
i从2到n-1变化时,令j从0到i-1变化,当nums[j]比num[i]小时,在tmp[j]+1中寻找最大值。
题解
class Solution {
public:
static bool cmp(int a,int b){
return a>b;
}
int lengthOfLIS(vector<int> &nums) {
int n = nums.size();
if (n == 0) return 0;
vector<int> tmp(n, 1);
for (int i = 1; i < n; i++) {
int cur = nums[i];
for (int j = 0; j < i; j++) {
if (cur > nums[j]) {
tmp[i] = max(tmp[j] + 1, tmp[i]);
}
}
}
sort(tmp.begin(), tmp.end(), cmp);
return tmp[0];
}
};