Thursday, February 28, 2013

Pascal's Triangle


/*

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

*/
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> result;
        vector<int> line;
        if(numRows <= 0) return result;
       
        if(numRows == 1) {
            line.push_back(1);
            result.push_back(line);
            return result;
        }
       
        result = generate(numRows-1);
        line = result.back();
        vector<int> temp;
        temp.push_back(1);
        int i;
        for(i=1; i<line.size(); i++){
            temp.push_back(line[i]+line[i-1]);
        }
        temp.push_back(1);
        result.push_back(temp);
       
        return result;
    }
};

No comments:

Post a Comment