-
Notifications
You must be signed in to change notification settings - Fork 1
/
pascals-triangle-ii.js
70 lines (64 loc) · 1.42 KB
/
pascals-triangle-ii.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Source: https://leetcode.com/problems/pascals-triangle-ii/
* Tags: [Array]
* Level: Easy
* Title: Pascal's Triangle II
* Auther: @imcoddy
* Content: Given an index k, return the kth row of the Pascal's triangle.
*
*
* For example, given k = 3,
* Return [1,3,3,1].
*
*
*
* Note:
* Could you optimize your algorithm to use only O(k) extra space?
*/
/**
* @param {number} rowIndex
* @return {number[]}
*/
/**
* Memo: Create the whole pascals triangle and return kth row
* Complex: O(n^2)
* Runtime: 120ms
* Tests: 34 test cases passed
* Rank: S
*/
var getRow = function(rowIndex) {
var result = [];
for (var i = 0; i <= rowIndex; i++) {
var row = [];
for (var j = 0; j <= i; j++) {
var val = 1;
if (j < i && j > 0 && i >= 1) {
val = result[i - 1][j - 1] + result[i - 1][j];
}
row.push(val);
}
result.push(row);
}
return result[rowIndex];
};
/**
* Memo: Use only O(k) extra space
* Complex: O(n^2)
* Runtime: 115ms
* Tests: 34 test cases passed
* Rank: S
*/
var getRow = function(rowIndex) {
var a = [];
for (var i = 0; i <= rowIndex; i++) {
a.push(1);
}
for (var i = 1; i <= rowIndex; i++) {
for (j = 1; j < i; j++) {
a[j] = a[rowIndex] + a[j];
a[rowIndex] = a[j] - a[rowIndex];
}
}
return a;
};
console.log(getRow(5));