Monday, November 25, 2013

LeetCode problem : Pascal's Triangle II

Problem


Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?

Code

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

No comments:

Post a Comment