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

注意左右的边界赋值

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> w;
        for (int i = 0; i < numRows; ++i) {
            vector<int>v(i + 1);
            int n = w.size();
            for (int j = 0; j <= i; ++j) {
                if (i == 0) v[0] = 1;
                else { 
                    if (j == 0) v[j] = w[n- 1][j];
                    else if (j == i) v[j] = w[n - 1][j - 1];
                    else v[j] = w[n - 1][j] + w[n - 1][j - 1];
                }
            }
            w.push_back(v);
        }
        return w;
    }
};

 

posted on 2017-07-24 12:19  Beserious  阅读(124)  评论(0编辑  收藏  举报