Leetcode: Pascal's Triangle

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]
]


 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<vector<int> > result;
 7         if (numRows < 1) return result;
 8         result.push_back(vector<int>(1,1));//first row (result[0])
 9         result.resize(numRows);
10         for(int ii = 1; ii < numRows; ++ii){
11             result[ii].resize(ii+1);
12             result[ii][0] = 1;
13             result[ii][ii] = 1;
14             for(int jj = 1; jj < ii; ++jj){
15                 result[ii][jj] = result[ii-1][jj-1] + result[ii-1][jj];
16             }
17         }
18         return result;
19     }
20 };

 

 1 vector<vector<int> > generate(int numRows) {
 2     vector<vector<int> > result;
 3     if (numRows <= 0) return result;
 4     result.push_back(vector<int>(1,1));
 5 
 6     for (int i = 1; i < numRows; i++) {
 7         vector <int> vec;
 8         for (int j = 0; j <= i; j++) {
 9             if (j == 0 || j == i) vec.push_back(1);
10             else vec.push_back(result.back()[j-1] + result.back()[j]);
11         }
12         result.push_back(vec);            
13     }
14     return result;
15 }

 

posted @ 2013-04-30 10:16  caijinlong  阅读(120)  评论(0编辑  收藏  举报