Monday, November 25, 2013

LeetCode Problem : Pascal's Triangle

Problem


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

Code

vector<vector<int> > generate(int numRows) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    vector<vector<int> > M(numRows);
    if(numRows == 0)
        return M;
    M[0].push_back(1);
    for(int i = 1; i < numRows;++i){
        M[i].push_back(M[i - 1][0]);
        for(int j = 1; j < i;++j){
         M[i].push_back(M[i - 1][j - 1] + M[i - 1][j]);
        }
        M[i].push_back(M[i - 1][i - 1]);
    }
    return M;
}

No comments:

Post a Comment