118.杨辉三角
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例: |
---|
输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] |
乍一看有点懵,其实还是很简单的。利用杨辉三角的性质就好。
就是在vector内存空间的申请这儿需要注意一下。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> nums;
int n;
for(int i = 0; i < numRows; i++){
nums.push_back(vector<int> (i+1, 1));
if(i > 1){
for(n = 1; n < i; n++)
nums[i][n] = nums[i-1][n]+nums[i-1][n-1];
}
}
return nums;
}
};
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.