forked from xingzhougmu/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriangle
80 lines (61 loc) · 2.28 KB
/
triangle
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
71
72
73
74
75
76
77
78
79
80
/*
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.
*/
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
// Start typing your Java solution below
// DO NOT write main() function
int sum = 0;
min_sum = Integer.MAX_VALUE;
if (triangle.size()==0) return sum;
min1(triangle); // o(n^2) operations
return triangle.get(0).get(0);
/*
min(triangle, 0, 0, 0); // dfs
return min_sum;
*/
/*
for (int i=0; i<triangle.size(); i++){
sum += minmum(triangle.get(i));
}
return sum;
*/
}
private static void min1(ArrayList<ArrayList<Integer>> triangle){
for (int i=triangle.size(); i>1; i--){
ArrayList<Integer> arrayLower = triangle.get(i-1);
ArrayList<Integer> arrayupper = triangle.get(i-2);
for (int j=0; j<arrayupper.size(); j++){
arrayupper.set(j, arrayupper.get(j)+Math.min(arrayLower.get(j), arrayLower.get(j+1)));
}
}
}
private static void min2(ArrayList<ArrayList<Integer>> triangle){
for (int i=triangle.size(); i>1; i--){
for (int j=0; j<triangle.get(i-2).size(); j++){
triangle.get(i-2).set(j, triangle.get(i-2).get(j)+Math.min(triangle.get(i-1).get(j), triangle.get(i-1).get(j+1)));
}
}
}
private static void min(ArrayList<ArrayList<Integer>> triangle, int sum, int d, int ind){
if (d == triangle.size()) {
min_sum = Math.min(min_sum, sum);
return;
}
ArrayList<Integer> array = triangle.get(d);
for (int i=ind; i<=Math.min(ind+1, array.size()-1); i++){
min(triangle, sum+array.get(i), d+1, i);
}
}
private static int min_sum = Integer.MAX_VALUE;
}