Uh oh!
There was an error while loading. Please reload this page.
forked from trekhleb/javascript-algorithms
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascalTriangleRecursive.js
More file actions
Latest commit
30 lines (24 loc) · 998 Bytes
/
Copy pathpascalTriangleRecursive.js
File metadata and controls
30 lines (24 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param {number} lineNumber - zero based.
* @return {number[]}
*/
exportdefaultfunctionpascalTriangleRecursive(lineNumber){
if(lineNumber===0){
return[1];
}
constcurrentLineSize=lineNumber+1;
constpreviousLineSize=currentLineSize-1;
// Create container for current line values.
constcurrentLine=[];
// We'll calculate current line based on previous one.
constpreviousLine=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(letnumIndex=0;numIndex<currentLineSize;numIndex+=1){
constleftCoefficient=(numIndex-1)>=0 ? previousLine[numIndex-1] : 0;
constrightCoefficient=numIndex<previousLineSize ? previousLine[numIndex] : 0;
currentLine[numIndex]=leftCoefficient+rightCoefficient;
}
returncurrentLine;
}