Saturday, April 11, 2015

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


Solution:
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > sol;
        vector<int> prev, curr;
        
        if (numRows == 0)
            return sol;
        
        // base;
        prev.push_back(1);
        sol.push_back(prev);
        
        for (int i = 0; i < numRows - 1; i++) {
            curr.push_back(1);
            int prev_size = prev.size();
            for (int prev_iter = 0; prev_iter < (prev_size - 1); prev_iter++) {
                curr.push_back(prev[prev_iter] + prev[prev_iter + 1]);
            }
            curr.push_back(1);
            sol.push_back(curr);
            // make prev ready for next iteration.
            prev = curr;
            curr.clear();
        }
        return sol;
    }
};

======= Online one =======

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > res;
        if (numRows==0){return res;}
        vector<int> r;
        r.push_back(1);
        res.push_back(r);
        if (numRows==1){return res;}
        r.push_back(1);
        res.push_back(r);
        if (numRows==2){return res;}
         
        for (int i=2;i<numRows;i++){
            vector<int> c(i+1,1);
            for (int j=1;j<i;j++){
                c[j]= res[i-1][j]+res[i-1][j-1];
            }
            res.push_back(c);
        }
        return res;
    }
};

No comments:

Post a Comment