top1编程
← 返回题目
题解

【基础】求子序列的个数

1 条题解

  • 0
    @ 2026-7-30 1:34:16

    解题思路

    记录当前是上升还是下降,方向改变时就开始了新的子序列。

    参考代码

    // 先读入题目给出的数据。
    // 再按照题目要求进行计算。
    // 最后按规定格式输出答案。
    #include <iostream>
    using namespace std;
    int main() {
        int n, a[10], cnt = 1, d, nd;
        cin >> n; for (int i = 0; i < n; i++) cin >> a[i];
        // d记录当前连续子序列是上升还是下降。
        d = a[1] > a[0] ? 1 : -1;
        for (int i = 2; i < n; i++) {
            nd = a[i] > a[i - 1] ? 1 : -1;
            // 方向改变时,说明开始了一个新的子序列。
            if (nd != d) { cnt++; d = nd; }
        }
        cout << cnt << endl;
        return 0;
    }
    

    复杂度分析

    排序需要 O(n^2) 时间;其余循环按照实际遍历次数计算。代码使用固定大小数组,额外空间复杂度为 O(1) 或 O(n)。

    • 1