用栈实现最长递增子序列c++
时间: 2023-08-02 17:08:47 浏览: 57
下面是使用栈实现最长递增子序列的 C++ 代码:
```c++
int findLongestIncreasingSubsequence(vector<int>& nums) {
stack<int> s;
for (int num : nums) {
if (s.empty() || num > s.top()) {
s.push(num);
} else {
auto it = lower_bound(nums.begin(), nums.end(), num);
*it = num;
}
}
return s.size();
}
```
该算法与前面提到的算法很类似,唯一的区别在于当发现一个数小于等于栈顶元素时,不直接将其替换掉,而是在原数组中找到第一个大于等于这个数的位置,将其替换为这个数。这样做的目的是为了保证栈中的元素是一个递增的序列。
该算法的时间复杂度为 $O(n \log n)$,其中 $n$ 是数组的长度,因为在查找第一个大于等于某个数的位置时使用了二分查找,而二分查找的时间复杂度是 $O(\log n)$。
相关问题
用栈实现最长递增子序列
下面是使用栈实现最长递增子序列的代码:
```c++
int findLongestIncreasingSubsequence(vector<int>& nums) {
stack<int> s;
for (int num : nums) {
if (s.empty() || num > s.top()) {
s.push(num);
} else {
auto it = lower_bound(nums.begin(), nums.end(), num);
*it = num;
}
}
return s.size();
}
```
该算法与前面提到的算法很类似,唯一的区别在于当发现一个数小于等于栈顶元素时,不直接将其替换掉,而是在原数组中找到第一个大于等于这个数的位置,将其替换为这个数。这样做的目的是为了保证栈中的元素是一个递增的序列。
该算法的时间复杂度为 $O(n \log n)$,其中 $n$ 是数组的长度,因为在查找第一个大于等于某个数的位置时使用了二分查找,而二分查找的时间复杂度是 $O(\log n)$。
最长递增子序列c++
最长递增子序列是一个常见的问题,可以使用动态规划来解决。以下是一个使用 C++ 实现的示例代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int longestIncreasingSubsequence(vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
vector<int> dp(n, 1); // dp[i]表示以nums[i]结尾的最长递增子序列长度
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);
}
}
}
int longest = 1;
for (int i = 0; i < n; i++) {
longest = max(longest, dp[i]);
}
return longest;
}
int main() {
vector<int> nums = {10, 9, 2, 5, 3, 7, 101, 18};
cout << "最长递增子序列的长度为:" << longestIncreasingSubsequence(nums) << endl;
return 0;
}
```
运行结果:
```
最长递增子序列的长度为:4
```
以上代码使用动态规划的思想,时间复杂度为 O(n^2),其中 n 是序列的长度。通过填充一个辅助数组 dp,每个元素 dp[i] 表示以第 i 个数字结尾的最长递增子序列的长度。然后遍历整个数组,更新 dp[i] 的值,最后返回 dp 数组中的最大值即为最长递增子序列的长度。