-
Notifications
You must be signed in to change notification settings - Fork 0
/
0120. Triangle.js
71 lines (62 loc) · 1.77 KB
/
0120. Triangle.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
// Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
// For example, given the following triangle
// [
// [2],
// [3,4],
// [6,5,7],
// [4,1,8,3]
// ]
// The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
// Note:
// Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
// 1) space: O(n^2)
/**
* @param {number[][]} triangle
* @return {number}
*/
const minimumTotal = function(triangle) {
if (triangle.length) {
if (triangle.length === 1 && triangle[0].length) {
return triangle[0][0]
} else {
// 每一行,由下到上,得到当前位置累加和的最小值
let min = []
let n = triangle.length
for (let i = n - 2; i >= 0; i--) {
min[i] = []
for (let j = 0; j < triangle[i].length; j++) {
min[i].push(triangle[i][j] + Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]))
}
triangle[i] = min[i]
}
return min[0][0]
}
}
}
// 2) space: O(n)
const minimumTotal = function(triangle) {
if (triangle.length) {
if (triangle.length === 1 && triangle[0].length) {
return triangle[0][0]
} else {
// 每一行,由下到上,得到当前位置累加和的最小值
let n = triangle.length
let min = triangle[n - 1]
for (let i = n - 2; i >= 0; i--) {
min = []
for (let j = 0; j < triangle[i].length; j++) {
min.push(
triangle[i][j] +
Math.min(triangle[i + 1][j], triangle[i + 1][j + 1])
)
}
triangle[i] = min
}
return min[0]
}
}
}
// Test case:
// [[-1],[2,3],[1,-1,-3]]
// [[1]]
// []