首页 > 代码库 > LeetCode118——Pascal's Triangle

LeetCode118——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行。

难度系数:容易

实现

vector<vector<int> > generate(int rowIndex) {
    vector<int> vi;
    vector<vector<int>> vvi;
    if (rowIndex == 0) {
        return vvi;
    }else if (rowIndex == 1) {
        vi.push_back(1);
        vvi.push_back(vi);
    }else {
        vvi = generate(rowIndex - 1);
        vector<int> tempv = vvi[rowIndex-2];
        for (int i = 0; i < rowIndex; ++i) {
            if (i == 0 || i == rowIndex-1) {
                vi.push_back(1);
            } else {
                vi.push_back(tempv[i-1] + tempv[i]);
            }
        }
        vvi.push_back(vi);
    }
    return vvi;
}

LeetCode118——Pascal's Triangle