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; }};