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

杨辉三角,周末了,来点轻松的。

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > result;
        vector<int> v, last;
        for (int i = 0; i < numRows; ++i) {
            v.clear();
            for (int j = 0; j <= i; ++j) {
                if (j == 0 || j == i) {
                    v.push_back(1);
                }
                else {
                    v.push_back(last[j-1] + last[j]);
                }
            }
            result.push_back(v);
            last = v;
        }
        
        return result;
    }
};

====================第二次======================

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> result;
        vector<int> row;
        for (int i = 0; i < numRows; ++i) {
            row.resize(i+1);
            for (int j = i; j >= 0; --j) {
                if (j == 0 || j == i) {
                    row[j] = 1;
                }
                else {
                    row[j] += row[j-1];
                }
            }
            result.push_back(row);
        }
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)