美文网首页LeetCode题解程序员
leetcode 118. Pascal's Triangle

leetcode 118. Pascal's Triangle

作者: 云胡同学 | 来源:发表于2017-07-26 13:33 被阅读0次


    题目描述

    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]

    ]

    思路

    很明显,杨辉三角,在欧洲称为帕斯卡三角形。

    找规律:

    1. 每一行的第一个和最后一个是1

    2. 杨辉三角的系数同时是二次项

    展开式中的第n行每一项的系数对应杨辉三角第n+1行每一项的系数。

    3.杨辉三角中上一行相邻的两个数相加等于这一行的值。

    结合2可得:

    将其展开也可验证是正确的。

    代码

    class Solution {

    public:

    vector< vector > generate(int numRows) {

    vector< vector > res(numRows);

    int i, j;

    for(i = 0; i < numRows; i++)

    {

        res[i].resize(i+1);//第i行分配i个列 不可一下子分配n行n列

        res[i][0] = 1;

        res[i][res[i].size()-1] = 1;

        for(j = 1; j < i; j++)

    {

        res[i][j] = res[i-1][j-1] + res[i-1][j];

    }

    }

        return res;

    }

    };

    相关文章

      网友评论

        本文标题:leetcode 118. Pascal's Triangle

        本文链接:https://www.haomeiwen.com/subject/hqwnkxtx.html