【算法-动态规划-简单】杨辉三角
AwesomeDevin opened this issue · comments
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
//最终结果
const res = []
// 当前行下标
let curRowIndex = 0
function dps(rowIndex){
const arr = []
if(rowIndex === 0){
// 第一行给默认值1
arr.push(1)
}else{
// 其它行根据前一行的数据进行计算
const lastArr = res[rowIndex-1]
// 当前行应有的数据长度
const rowLength = rowIndex + 1
while(arr.length < rowLength){
// 前一行的左侧下标
const index1 = arr.length-1
// 前一行的右侧下标
const index2 = arr.length
// 前一行左侧值
const val1 = index1 >=0 ? lastArr[index1] : 0
// 前一行右侧值
const val2 = lastArr[index2] || 0
// push计算结果到当前行
arr.push(val1 + val2)
}
}
// push 当前行 到 res
res.push(arr)
}
// 从第一行开始计算到最后一行
while(curRowIndex<numRows){
dps(curRowIndex)
curRowIndex++
}
return res
};