Triangle
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(List<List<Integer>> triangle) {
int total = 0;
int[][] sum = new int[triangle.size()][];
for (int i = 0; i < triangle.size(); i++)
sum[i] = new int[triangle.get(i).size()];
sum[0][0] = triangle.get(0).get(0);
for (int i = 1; i < triangle.size(); i++)
sum[i][0] = sum[i - 1][0] + (int) triangle.get(i).get(0);
for (int i = 1; i < triangle.size(); i++)
sum[i][triangle.get(i).size() - 1] = sum[i - 1][triangle.get(i - 1)
.size() - 1]
+ triangle.get(i).get(triangle.get(i).size() - 1);
for (int i = 2; i < triangle.size(); i++)
for (int j = 1; j < triangle.get(i).size() - 1; j++)
if (sum[i - 1][j - 1] > sum[i - 1][j])
sum[i][j] = sum[i - 1][j] + triangle.get(i).get(j);
else
sum[i][j] = sum[i - 1][j-1] + triangle.get(i).get(j);
total = sum[triangle.size() - 1][0];
for (int i = 1; i < triangle.get(triangle.size() - 1).size(); i++)
if (total > sum[triangle.size() - 1][i])
total = sum[triangle.size() - 1][i];
return total;
}
}
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int total = 0;
int[][] sum = new int[triangle.size()][];
for (int i = 0; i < triangle.size(); i++)
sum[i] = new int[triangle.get(i).size()];
sum[0][0] = triangle.get(0).get(0);
for (int i = 1; i < triangle.size(); i++)
sum[i][0] = sum[i - 1][0] + (int) triangle.get(i).get(0);
for (int i = 1; i < triangle.size(); i++)
sum[i][triangle.get(i).size() - 1] = sum[i - 1][triangle.get(i - 1)
.size() - 1]
+ triangle.get(i).get(triangle.get(i).size() - 1);
for (int i = 2; i < triangle.size(); i++)
for (int j = 1; j < triangle.get(i).size() - 1; j++)
if (sum[i - 1][j - 1] > sum[i - 1][j])
sum[i][j] = sum[i - 1][j] + triangle.get(i).get(j);
else
sum[i][j] = sum[i - 1][j-1] + triangle.get(i).get(j);
total = sum[triangle.size() - 1][0];
for (int i = 1; i < triangle.get(triangle.size() - 1).size(); i++)
if (total > sum[triangle.size() - 1][i])
total = sum[triangle.size() - 1][i];
return total;
}
}