[LeetCode 解题报告]118. Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
] 
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        if (numRows <= 0)
            return {};
        
        vector<vector<int>> res(numRows, vector<int>(1));
        for (int i = 0; i < numRows; i ++) {
            res[i][0] = 1;
            
            for (int j = 1; j < i; j ++) {
                res[i].push_back(res[i-1][j-1] + res[i-1][j]);
            }
            if (i == 0)
                continue;
            res[i].push_back(1);
        }
        return res;
    }
};
发布了401 篇原创文章 · 获赞 39 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/103723992