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]
]
C++:
01 class Solution {
02 public:
03     vector<vector<int> > generate(int numRows) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         vector<vector<int> > result;
07         if(numRows==0)
08             return result;
09         vector<int> first;
10         first.push_back(1);
11         result.push_back(first);
12         for(int i=1;i<numRows;i++)
13         {
14             vector<int> prev=result[i1];
15             vector<int> A(i+1);
16             A[0]=A[i]=1;
17             for(int j=1;j<i;j++)
18             {
19                 A[j]=prev[j1]+prev[j];
20             }
21             result.push_back(A);
22         }
23         return result;
24     }
25 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s