Pascal's Triangle
leetcode
题意
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]
]
思路:
这道题比较简单,属于基础的数组操作。基本思路是每层保存前一行的指针,然后当前航数据根据上一行来得到,每个元素就是上一行两个相邻元素相加(第一个和最后一个元素是1)。
。
code
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > res;
if(numRows <= 0) return res;
vector<int> firstArr;
firstArr.push_back(1);
res.push_back(firstArr);
if(numRows == 1) {
return res;
}
for(int i = 1; i < numRows; i++) {
res.push_back(nextRow(res[i - 1]));
}
return res;
}
vector<int> nextRow(const vector<int>& pre) {
int len = pre.size();
vector<int> next(len + 1);
next[0] = next[len] = 1;
for(int i = 1; i < len; i++) {
next[i] = pre[i - 1] + pre[i];
}
return next;
}
};