Skip to content

Instantly share code, notes, and snippets.

@motss
Created August 30, 2019 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motss/40f912a80f9538932d7c6a3944764a42 to your computer and use it in GitHub Desktop.
Save motss/40f912a80f9538932d7c6a3944764a42 to your computer and use it in GitHub Desktop.
Pascal's triangle with n level
// Time complexity: O(n ^ 2) where is the number of levels and
// another n is for the number of elements in each level.
// Space complexity: O(2n + 1) to hold all elements, which is linear space.
function pascalTriangle(level) {
if (level === 0) return [];
if (level === 1) return [1];
if (level === 2) return [1, 1];
const d = Array.from(Array(level), () => []);
d[0] = [1];
d[1] = [1, 1];
for (let i = 2; i < level; i += 1) {
const arr = Array.from(Array(i + 1), () => 1);
for (let j = 1; j < i; j += 1) {
arr[j] = d[i - 1][j - 1] + d[i - 1][j];
}
d[i] = arr;
}
return d;
}
function main() {
Array.from(Array(20), (_, i) => {
console.log(`Pascal's triangle with %d level(s): `, i, pascalTriangle(i));
});
}
console.clear();
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment