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]]
1 class Solution { 2 public: 3 vector<vector<int> > generate(int numRows) { 4 vector<vector<int>> sols; 5 if(numRows==0)return sols; 6 vector<int> pre(1,1); 7 sols.push_back(pre); 8 for(int i=1;i<numRows;i++) 9 {10 vector<int> cur;11 cur.push_back(1);12 for(int j=1;j<i;j++)13 {14 cur.push_back(sols[i-1][j-1]+sols[i-1][j]);15 }16 cur.push_back(1);17 sols.push_back(cur);18 }19 return sols;20 }21 };Pascal's triangle II
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?
Idea: You can use an array by adding the following code.
1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 vector<int> sols(1,1); 5 for(int i=1;i<rowIndex+1;i++) 6 { 7 sols.resize(i+1,0); 8 for(int j=sols.size()-1;j>=1;j--) 9 {10 sols[j]=sols[j]+sols[j-1];//!!!!11 }12 }13 return sols;14 15 }16 };