杭电OJ 2032杨辉三角

杨辉三角
杨辉三角形这一题型,属于分治法,如果我们使用递归来处理,可以解决但是时间复杂度太高,为\(O(2^n)\),会超时错误,所以应该用递推法,一行一行的把值保存下来,减少大量的重复计算,这样时间复杂度为\(O(n)\),还不错。

当然解题思路,无论是递归还是递推,都是一样的,总结递归公式、及递归出口(可能不止一个)。

#include <iostream>
#include <cstdio>

using namespace std;
const int MAXN = 30 + 5;

struct Triangle {
    int arr[MAXN][MAXN];
    int row, col;
};
Triangle answer;

//递推法求杨辉三角形
void yang_triangle(int n) {
    for(int i = 1; i <= n; ++i) {
        for(int j = 0; j < i; ++j) {
            if(j == 0 || j == i - 1) {
                answer.arr[i-1][j] = 1;
            } else {
                answer.arr[i-1][j] = answer.arr[i-2][j-1] + answer.arr[i-2][j];
            }
        }
    }
}

int main()
{
    int n;
    while(cin >> n) {
        yang_triangle(n);
        //output
        for(int i = 1; i <= n; ++i) {
            for(int j = 0; j < i; ++j) {
                if(j == 0) {
                    cout << answer.arr[i-1][j];
                } else {
                    cout << " " << answer.arr[i-1][j];
                } 
            }
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}
posted @ 2024-03-10 16:48  paopaotangzu  阅读(51)  评论(0)    收藏  举报