-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
52 lines (50 loc) · 1.11 KB
/
index.ts
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* # 118. Pascal's Triangle
*
* Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
*
* 
*
* ###### In Pascal's triangle, each number is the sum of the two numbers directly above it.
*
* ## Example
*
* ```bash
* Input: 5
* Output:
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
* ```
*/
export type Solution = (numRows: number) => number[][];
/**
* 杨辉三角形
* (n,k) = (n-1,k-1) + (n-1,k)
* (n,k) = n!/k!(n-k)! 第 n 行,第 k 个元素
* @date
* @time
* @space
* @runtime
* @memory
* @runtime_cn 44 ms, faster than 99.04%
* @memory_cn 33.9 MB, less than 41.52%
*/
export const pascalTriangle = (numRows: number): number[][] => {
if (numRows === 0) {
return [];
}
const triangle: number[][] = [[1]];
for (let i = 1; i < numRows; i += 1) {
const row: number[] = [];
for (let j = 0; j <= i; j += 1) {
row[j] = (triangle[i - 1][j - 1] || 0) + (triangle[i - 1][j] || 0);
}
triangle.push(row);
}
return triangle;
};