Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Return
[1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
Could you optimize your algorithm to use only O(k) extra space?
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<int> getRow(int numRows) { | |
numRows++; | |
vector<int> newRow; | |
vector<int> lastRow; | |
for(int i=1; i<=numRows; i++){ | |
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]); | |
} | |
lastRow=newRow; | |
newRow.clear(); | |
} | |
return lastRow; | |
} | |
}; |
No comments:
Post a Comment