Pascal's Triangle -- leetcode

来源:互联网 发布:时时彩计划网站源码 编辑:程序博客网 时间:2024/06/01 11:20

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

基本思路:

每行比上行多一个元素。

每行第一列和最后一列,均为1。

其他列为上一行的当前列和前一列之和。

class Solution {public:    vector<vector<int>> generate(int numRows) {        vector<vector<int>> ans(numRows);        for (int i=0; i<numRows; i++) {            for (int j=0; j<=i; j++) {                ans[i].push_back(j!=0 && j!=i ? ans[i-1][j] + ans[i-1][j-1] : 1);            }        }        return ans;    }};


0 0
原创粉丝点击