1 条题解

  • 0
    @ 1981-7-25 2:21:50

    练38.3 空心菱形

    解题思路

    菱形共2n-1行。第i行距中心k,外侧补k空格,左右端点相距2(n-k)-2;端点间填空格。顶底两端点重合。

    正确性说明

    计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。

    易错点

    只有边界星号,不能把内部填满。

    复杂度

    时间O(n²),空间O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        for (int i = 0; i < 2 * n - 1; i++) {
            int k = abs(i - n + 1), w = 2 * (n - k) - 1;
            cout << string(k, ' ') << "*";
            if (w > 1)
                cout << string(w - 2, ' ') << "*";
            cout << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    264
    时间
    1000ms
    内存
    64MiB
    难度
    进阶
    标签
    递交数
    0
    已通过
    0
    上传者