LeetCode (13) Pascal & #39; s Triangle (Yang Hui Triangle), leetcodetriangle

Source: Internet
Author: User

LeetCode (13) Pascal's Triangle (Yang Hui Triangle), leetcodetriangle
Description

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

Starting from the third row, each row has one to the leftmost and rightmost numbers, and the other numbers are the sum of the two adjacent numbers in the previous row. Based on the above rules, you can write the following code:

class Solution {public:    vector<vector<int> > generateRow1() {        vector<int> row;        row.push_back(1);        vector<vector<int>> r;        r.push_back(row);        return r;    }    vector<vector<int> > generateRow2() {        vector<vector<int>> r = generateRow1();        vector<int> row;        row.push_back(1);        row.push_back(1);        r.push_back(row);        return r;    }    vector<vector<int> > generate(int numRows) {        if (numRows < 1)        {            vector<vector<int> > r;            return r;        }        if (numRows == 1)            return generateRow1();        if (numRows == 2)            return generateRow2();        vector<vector<int> > r = generateRow2();        for (int i = 2; i != numRows; ++i)        {            vector<int> row;            row.push_back(1);            for(int j = 1; j != i; ++j)            {                int next = r[i-1][j-1] + r[i-1][j];                row.push_back(next);            }            row.push_back(1);            r.push_back(row);        }        return r;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.