Thursday, September 25, 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]
]
Analysis:

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > ret;
        for(int i=0; i<numRows; i++)
        {
            vector<int> row;
            for(int j=0; j<=i; j++)
            {
                //first and last one is 1, others are the sum of current and last pos of last line
                if (j == 0 || j == i)
                    row.push_back(1);
                else
                    row.push_back(ret[i-1][j] + ret[i-1][j-1]);
            }
            ret.push_back(row);
        }
        return ret;
    }
};

No comments:

Post a Comment