题目描述(难度:简单)
- 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
- 在杨辉三角中,每个数是它左上方和右上方的数的和。
代码
var generate = function (numRows){
const result = [];
if (numRows <= 0) {
return result;
}
for (let i = 0; i < numRows; i ++) {
const subArr = [];
for (let j = 0; j <= i; j++) {
if (j > 0 && j < i) {
subArr.push(result[i-1][j-1] + result[i-1][j]);
} else {
subArr.push(1);
}
}
result.push(subArr);
}
return result[result.length-1];
}
var getRow = function(rowIndex) {
let triangle = [];
if (rowIndex > -1) triangle = [1];
if (rowIndex > 0) triangle = [1, 1];
for(let i = 1; i < rowIndex ; i++) {
let temp = triangle;
triangle = [1];
for(let j = 1; j < temp.length; j++) {
triangle.push(temp[j] + temp[j-1]);
}
triangle.push(1);
}
return triangle;
};
var getRow = function(rowIndex) {
let triangle = [];
if (rowIndex > -1) triangle.push([1]);
if (rowIndex > 0) triangle.push([1, 1]);
for(let i = 1; i < rowIndex ; i++) {
triangle.push([1]);
for(let j = 0; j < triangle[i].length - 1; j++) {
triangle[i+1].push(triangle[i][j] + triangle[i][j+1]);
}
triangle[i+1].push(1);
}
return triangle[rowIndex];
};