Skip to content

Latest commit

 

History

History
57 lines (46 loc) · 1.26 KB

0118. 杨辉三角 [Easy] [Pascal's Triangle].md

File metadata and controls

57 lines (46 loc) · 1.26 KB

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

img 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]
]

题目:给定一个非负整数 *numRows,*生成杨辉三角的前 numRows 行。

思路

工程代码下载

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> res;
        if(numRows == 0)
            return res;
        res.push_back({1});
        if(numRows == 1)
            return res;
        res.push_back({1, 1});
        if(numRows == 2)
            return res;

        for(int i = 2; i < numRows; ++i){
            vector<int> vec;
            vec.push_back(1);
            for(int i = 0; i < res.back().size()-1; ++i){
                vec.push_back(res.back()[i] + res.back()[i+1]);
            }
            vec.push_back(1);
            res.push_back(vec);
        }

        return res;
    }
};