leetcode Pascal's Triangle

来源:互联网 发布:淘宝开店资料出售 编辑:程序博客网 时间:2024/06/05 05:22

Pascal's Triangle

 Total Accepted: 18780 Total Submissions: 59362My Submissions

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

Have you been asked this question in an interview? 

Discuss

杨辉三角,这个规律写下来,不是很难,注意开头结尾不同就行了。

//10:06 ->10:13 ->10:16class Solution {public:    vector<vector<int> > generate(int numRows) {        vector<vector<int> > res;        if(numRows==0)        {            return res;        }        vector<int> row1(1,1);        res.push_back(row1);        for(int i=1;i<numRows;i++)        {            vector<int> row2(i+1,0);            for(int j=0;j<=i;j++)            {                if(j==0)                {                    row2[j] = res[i-1][j]; // for the i-1                }else if(j==i)                {                    row2[j] =  res[i-1][j-1];                }else //add from the j and j-1                {                    row2[j] = res[i-1][j-1] + res[i-1][j];                }            }            res.push_back(row2);        }        return res;    }};


0 0
原创粉丝点击