LeetCode 118 Pascal's Triangle

来源:互联网 发布:阿里云邮箱手机客户端 编辑:程序博客网 时间:2024/05/21 07:55

题目:

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]]
题目链接

题意:

给一个行数,代表的是Pascal三角形的层数,要求用vector存储Pasicl三角,并将其返回。

通过观察可以得知,Pasicl三角的第i层有i个元素,且对于非首行,非首列,非末列的元素而言,元素的值等于上一层左右连个节点之和,即

nums[i][j] = nums[i-1][j-1] + nums[i-1][j]。

代码如下:

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