Leetcode: Pascal's Triangle
GivenNumrows, Generate the firstNumrowsOf Pascal's triangle.
For example, givenNumrows= 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
Address: https://oj.leetcode.com/problems/pascals-triangle/
Algorithm: Pascal's triangle is characterized by the sum of the J elements of the I + 1 line and the J elements of the J-1, of course, the first and end elements must be specially processed. To master this feature, it is not difficult to write the code:
1 class Solution { 2 public: 3 vector<vector<int> > generate(int numRows) { 4 vector<vector<int> > result; 5 if(numRows < 1){ 6 return result; 7 } 8 result.push_back(vector<int>(1,1)); 9 for(int i = 1; i < numRows; ++i){10 vector<int> temp(i+1);11 temp[0] = 1;12 temp[i] = 1;13 for(int j=1; j < i; ++j){14 temp[j] = result[i-1][j] + result[i-1][j-1];15 }16 result.push_back(temp);17 }18 return result;19 }20 };
Question 2:
Given an indexK, ReturnKTh row of the Pascal's triangle.
For example, givenK= 3,
Return[1,3,3,1]
.
Note:
Cocould you optimize your algorithm to use onlyO(K) Extra space?
Address: https://oj.leetcode.com/problems/pascals-triangle-ii/
Algorithm: To generate an array of the K rows, you must first generate an array of the K-1 rows, but it has nothing to do with the array of the K-2 rows, so we can use the method in the previous article to limit space, and the method of generating arrays is the same as that in the first question. Code:
1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 if(rowIndex < 0) return vector<int>(); 5 if(rowIndex == 0) return vector<int>(1,1); 6 vector<int> result1(rowIndex+1); 7 vector<int> result2(rowIndex+1); 8 result1[0] = 1; 9 vector<int> *pre = &result1;10 vector<int> *p = &result2;11 for(int i = 1; i <= rowIndex; ++i){12 (*p)[0] = 1;13 (*p)[i] = 1;14 for(int j = 1; j < i; ++j){15 (*p)[j] = (*pre)[j] + (*pre)[j-1];16 }17 vector<int> *temp = pre;18 pre = p;19 p = temp;20 }21 return *pre;22 }23 };
Leetcode: Pascal's Triangle