2014.1.8 22:44
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Solution:
Pascal's Triangle is a typical O(n^2) dynamic programming problem. Here is the recurrence relation:
1. f[i][0] = 1, i ∈ N
2. f[i][i] = 1, i ∈ N
3. f[i][j] = f[i - 1][j - 1] + f[i - 1][j], i ∈ N+, j ∈ N ∩ [0, i - 1]
Time complexity is O(n^2). Space complexity is O(1).
Accepted code:
1 // Too careless, 2WA!! 2 class Solution { 3 public: 4 vector<vector<int> > generate(int numRows) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 result.clear(); 8 9 if(numRows <= 0){ 10 return result; 11 } 12 13 int i, j; 14 for(i = 0; i < numRows; ++i){ 15 result.push_back(vector<int>()); 16 for(j = 0; j <= i; ++j){ 17 result[i].push_back(0); 18 } 19 } 20 21 for(i = 0; i < numRows; ++i){ 22 result[i][i] = result[i][0] = 1; 23 } 24 25 for(i = 1; i < numRows; ++i){ 26 for(j = 1; j < i; ++j){ 27 result[i][j] = result[i - 1][j] + result[i - 1][j - 1]; 28 } 29 } 30 31 return result; 32 } 33 private: 34 vector<vector<int>> result; 35 };