【LeetCode】139.Pascal's Triangle
阿新 • • 發佈:2018-12-21
題目描述(Easy)
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
題目連結
Example 1:
Input: 5 Output: [ [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; if (numRows < 1) return result; if (numRows == 1) return vector<vector<int>>{{1}}; if (numRows == 2) return vector<vector<int>>{{1}, {1, 1}}; result = vector<vector<int>>{{1}, {1, 1}}; int i = 3; for (int i = 3; i <= numRows; ++i) { vector<int> temp(i, 1); for (int j = 1; j < i - 1; ++j) { temp[j] = result[i - 2][j - 1] + result[i - 2][j]; } result.push_back(temp); } return result; } };