Saturday, September 20, 2014

LeetCode: Pascal 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]
]



    #define tr(v,it) for(decltype((v).begin()) it = (v).begin(); it != (v).end(); it++)


    vector<vector<int> > generate(int numRows) {  
     vector<vector<int> > v;  
     if (numRows<=0)return v;  
     v.push_back(vector<int> (1,1));  
     int i = 1;  
     while(i<numRows)  
     {  
       vector<int> x;  
       x.push_back(1);  
       int n = v[i-1].size();  
       tr(v[i-1], it)  
       {  
         int index = it - v[i-1].begin();  
         if(index < n-1){  
           x.push_back(*it + *(it+1));  
         }  
       }  
       x.push_back(1);  
       v.push_back(x);  
       i++;  
     }  
     return v;  
   }  

No comments:

Post a Comment