118. Pascal's Triangle

纵然是瞬间 提交于 2019-12-04 06:25:05

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]
]
Accepted
303,176
Submissions
622,830
 
 
 
 
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> res(numRows, vector<int>());
        if(0==numRows)return res;
        res[0].push_back(1);
        if(1==numRows)return res;
        for (int i = 1; i < numRows; ++i)
            for (int j = 0; j < i+1; ++j)
            {
                if (res[i].size() < i+1) res[i].resize(i+1);
                if (0 == j || i == j)res[i][j] = 1;
                else
                {
                    if (j) res[i][j] += res[i - 1][j - 1];
                    if (i >= j) res[i][j] += res[i - 1][j];
                }
            }
        return res;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!