Tuesday, May 27, 2014

LeetCode: Pascal's Triangle II

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?


Just follow the definition and generate row by row.

C++ Code:

/*
 * func: generate_pascal_row
 * goal: generate the specific row of pascal triangle
 * @param rowIndex: input row number
 * return: that row
 */
vector<int> generate_pascal_row(int rowIndex){
    vector<int> row;
    if(rowIndex < 0){
        return row;
    }
    row.resize(rowIndex+2);
    for(int i=0; i<rowIndex + 2; ++i){
        row[i] = 0;
    }
    row[1] = 1;
    for(int i=0; i<rowIndex; ++i){
        for(int j = rowIndex+1; j > 0; j--){
            row[j] = row[j-1] + row[j];
        }
    }
    row.erase(row.begin());
    return row;
}

Python Code:

# func: generate specific pascal row
# @param rowIndex: given row index
# @return: specific pascal row
def generate_pascal_row(rowIndex):
    if rowIndex < 0:
        return []
    result = [0,1,0]
    for _ in xrange(0, rowIndex):
        result = [0] + [result[i] + result[i+1] for i in xrange(len(result)-1)] + [0]
        print result

    return result[1:-1]

Reference Link:

1. 水中的鱼: [LeetCode] Pascal's Triangle II 解题报告: http://fisherlei.blogspot.com/2012/12/leetcode-pascals-triangle-ii.html

No comments:

Post a Comment