Tuesday, May 27, 2014

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


We can generate each row based on the definition, each element is the sum of the number above and to the left with the number above and to the right.

C++ Code:

/*
 * func: generate_pascal_triangle
 * goal: to generate input number of rows of pascal triangle
 * @param numRows: numer of rows
 * return: all rows
 */
vector<vector<int> > generate_pascal_triangle(int numRows){
    vector<vector<int> > result;
    if(numRows < 1){
        return result;
    }
    vector<int> row(1, 1);
    result.emplace_back(row);
    for(int i=0; i<numRows-1; ++i){
        vector<int> prev = result.back();
        vector<int> curr;
        for(int j = 0; j < prev.size()+1; ++j){
            if(j == 0 || j == prev.size()){
                curr.emplace_back(1);
            }else{
                curr.emplace_back(prev[j-1] + prev[j]);
            }
        }
        result.emplace_back(curr);
    }
    return result;
}

Python Code:

# func: generate pascal triangle
# @param numRows: given number of rows
# @return: all rows generated
def generate_pascal_triangle(numRows):
    if numRows < 1:
        return []
    result = [[1]]
    for _ in xrange(1, numRows):
        prev = [0] + result[-1] + [0]
        curr = []
        for i in xrange(len(prev)-1):
            curr.append(prev[i] + prev[i+1])
        result.append(curr)

    return result

No comments:

Post a Comment