1 1 1
2 1 2 1
3 1 3 3 1
Get each line from previous line. And set the beginning and ending to be 1.
Note the number of elements in each row is one bigger than the row index. So notice condition at Line7
O(n^2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> result; for(int i=0; i<numRows; i++){ vector<int> row; for(int j=0; j<=i;j++){ //NOTE: <=i or <i+1 if(j==0 || j==i) { row.push_back(1); continue; } row.push_back(result[i-1][j-1]+result[i-1][j]); } result.push_back(row); } return result; } }; |
没有评论:
发表评论