Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Solution:
Pascal's Triangle: Each element of current row, expect the boundary elements, is the sum of two elements that are directly on the above row.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> generate(int numRows) { | |
vector<vector<int> > res; | |
if(numRows==0) | |
return res; | |
for(int i=1; i<=numRows; i++){ | |
vector<int> newRow; | |
vector<int> lastRow; | |
if(i>2) | |
lastRow=res[i-2]; | |
for(int j=1; j<=i;){ | |
if(j==1||j==i){ | |
newRow.push_back(1); | |
j++; | |
} | |
else | |
for(int k=0; k<lastRow.size()-1; ++k, ++j) | |
newRow.push_back(lastRow[k]+lastRow[k+1]); | |
} | |
res.push_back(newRow); | |
} | |
return res; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> generate(int numRows) { | |
vector<vector<int> > res; | |
if(numRows==0) | |
return res; | |
vector<int> row(1, 1); | |
res.push_back(row); | |
for(int i=2; i<=numRows; i++){ | |
vector<int> row(i, 0); | |
vector<int> preRow=res.back(); | |
for(int j=0; j<i; j++) | |
row[j]= (j==0||j==i-1)? 1:(preRow[j-1]+preRow[j]); | |
res.push_back(row); | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment