LeetCode 之 Pascal's Triangle — C++ 实现

来源:互联网 发布:wps h5是什么软件 编辑:程序博客网 时间:2024/06/06 09:23

Pascal's 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 行杨辉三角。

例如,当 numRows = 5 时,返回

[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]
分析:

杨辉三角每行第一个和最后一个数为1,其它的数为上一行相邻两个数的和。

class Solution {public:    vector<vector<int>> generate(int numRows) {        if(numRows == 0) /* 0行 */            return vector<vector<int>>();                int row = 0, col = 0;        vector<vector<int>> retVec;                while(row < numRows)        {            vector<int> c;            for(col = 0; col <= row; ++col)            {                c.push_back((col == 0 || col == row)?1:(retVec[row-1][col-1]+retVec[row-1][col]));            }            retVec.push_back(c);            ++row;        }                return retVec;    }};

0 0
原创粉丝点击