letecode [118] - Pascal's Triangle
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:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题目大意:
输出前n行的杨辉三角,用二维vector表示。
理 解 :
初始化前2行的结果。第3-n行,利用前一行的累加获得。
代码C++:
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> vec; if(numRows==0) return vec; vector<int> rowVec; rowVec.push_back(1); vec.push_back(rowVec); if(numRows==1) return vec; rowVec.push_back(1); vec.push_back(rowVec); if(numRows==2) return vec; int i=3; while(i<=numRows){ rowVec.clear(); rowVec.resize(i); rowVec[0] = 1; int j = 1; while(j<i-1){ rowVec[j] = vec[i-2][j-1] + vec[i-2][j]; ++j; } rowVec[i-1] = 1; vec.push_back(rowVec); ++i; } return vec; } };
运行结果:
执行用时 : 0 ms 内存消耗 : 8.8 MB