Ai
1 Star 0 Fork 81

zhizou/javascript-algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pascalTriangleRecursive.js 998 Bytes
一键复制 编辑 原始数据 按行查看 历史
Oleksii Trekhleb 提交于 2018-07-07 16:11 +08:00 . Add Pascal's triangle.
/**
* @param {number} lineNumber - zero based.
* @return {number[]}
*/
export default function pascalTriangleRecursive(lineNumber) {
if (lineNumber === 0) {
return [1];
}
const currentLineSize = lineNumber + 1;
const previousLineSize = currentLineSize - 1;
// Create container for current line values.
const currentLine = [];
// We'll calculate current line based on previous one.
const previousLine = pascalTriangleRecursive(lineNumber - 1);
// Let's go through all elements of current line except the first and
// last one (since they were and will be filled with 1's) and calculate
// current coefficient based on previous line.
for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) {
const leftCoefficient = (numIndex - 1) >= 0 ? previousLine[numIndex - 1] : 0;
const rightCoefficient = numIndex < previousLineSize ? previousLine[numIndex] : 0;
currentLine[numIndex] = leftCoefficient + rightCoefficient;
}
return currentLine;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/zhizous/javascript-algorithms.git
git@gitee.com:zhizous/javascript-algorithms.git
zhizous
javascript-algorithms
javascript-algorithms
master

搜索帮助