pascals triangle(杨辉三角、帕斯卡三角)

题目描述

Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return:

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

题目大意

杨辉三角
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和正上方的数的和。
示例:
输入:
5
输出:

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

思路

每行比上一行多一个数,每行的第一个数和最后一个数为1,其他的位置的数等于它左上方和正上方的数的和。

代码

#include<iostream>
#include<vector>
using namespace std;

/**
 * 杨辉三角
 */
vector<vector<int> > generate(int numRows)
{
    vector<vector<int> > res;

    for(int i=0; i<numRows; i++)
    {
        vector<int > tmp(i+1, 1); // 数组空间为i+1,数组全部初始化为1

        for(int j=1; j<i; j++)
        {
            // 当前的数值是上方和左上方数值之和
            tmp[j] = res[i-1][j-1] + res[i-1][j];
        }

        res.push_back(tmp);
    }

    return res;
}

vector<vector<int> > generate_1(int numRows)
{
    vector<vector<int> > res;

    for(int i=0; i<numRows; i++)
    {
        vector<int > tmp; // 数组空间为i+1,数组全部初始化为1

        for(int j=0; j<=i; j++)
        {
            // 每行第一个数和最后一个数为1
            if(j==0 || j==i)
                tmp.push_back(1);
            // 其他位置的数遵循规则
            else
                tmp.push_back(res[i-1][j-1] + res[i-1][j]);
        }

        res.push_back(tmp);
    }

    return res;
}

int main()
{
    vector<vector<int> > a = generate(5);

    for(int i=0; i<a.size(); i++)
    {
        for(int j=0; j<a[i].size(); j++)
        {
            cout<<a[i][j]<<' ';
        }

        cout<<endl;
    }

    return 0;
}

运行结果

《pascals triangle(杨辉三角、帕斯卡三角)》

以上。

点赞