思路分析
很简单,就是每一行的出去第一个和最后一个之外的节点都是上一行的左右节点之和,对应下面的:
line_vec.push_back(prev_vec[j-1] + prev_vec[j]);代码实现
自己的实现
class Solution { public: vector> generate(int numRows) { vector > res; vector tmp; if (numRows == 0) { // res.push_back(tmp); // 空结果,不用再多此一举赋值了 return res; } tmp.push_back(1); res.push_back(tmp); if (numRows == 1) { return res; } for (int i = 2; i <= numRows; i++) { vector line_vec; for (int j = 0; j < i; j++) { if (j == 0 || j == i - 1) { line_vec.push_back(1); continue; } vector prev_vec = res[i - 2]; line_vec.push_back(prev_vec[j-1] + prev_vec[j]); } res.push_back(line_vec); } return res; }};复制代码
网友的实现,更简洁:
class Solution { public: vector> generate(int numRows) { vector > res(numRows, vector ()); for (int i = 0; i < numRows; ++i) { res[i].resize(i + 1, 1); for (int j = 1; j < i; ++j) { res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; } } return res; }};复制代码