问题描述:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if(numRows == 0) return res;
vector<int> temp;
if(numRows <= 2)
{
temp.push_back(1);
res.push_back(temp);
if(numRows == 1)
{
return res;
}
temp.push_back(1);
res.push_back(temp);
return res;
}
// 此处需要重新把 1/2行初始化。
temp.push_back(1);
res.push_back(temp);
temp.push_back(1);
res.push_back(temp);
temp.clear(); // 注意清空临时temp
int n = 3;
while(n <= numRows)
{
temp.push_back(1);
for(int i = 0; i < res[n-2].size() - 1; ++i) // 由于n是从1开始的,所以此处需要-2
{
temp.push_back(res[n-2][i] + res[n-2][i+1]);
}
temp.push_back(1);
res.push_back(temp);
temp.clear(); // 每次用完,都需要清空
++n;
}
return res;
}
};