From : https://leetcode.com/problems/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).
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size() == 0 || triangle[0].size() == 0) return 0;
vector<int> mins;
mins.push_back(triangle[0][0]);
for(int i=1, rows=triangle.size(); i<rows; i++) {
mins.push_back(triangle[i][i]+mins[i-1]);
for(int j=i-1; j>0; j--) {
mins[j] = min(mins[j], mins[j-1])+triangle[i][j];
}
mins[0] += triangle[i][0];
}
int min = INT_MAX;
for(int i=mins.size()-1; i>=0; i--) {
if(min > mins[i]) min = mins[i];
}
return (min!=INT_MAX)*min;
}
};
public class Solution {
public int minimumTotal(List<List<Integer>> t) {
if (t == null || t.size() == 0 || t.get(0) == null
|| t.get(0).size() == 0) {
return 0;
}
int[] candidates = new int[t.size()];
candidates[0] = t.get(0).get(0);
for (int i = 1; i < t.size(); ++i) {
List<Integer> cur = t.get(i);
for (int j = i; j >= 0; --j) {
if (j == 0 || j == i) {
if (j == 0) {
candidates[0] += cur.get(0);
} else {
candidates[j] = candidates[j - 1] + cur.get(j);
}
} else {
candidates[j] = cur.get(j)
+ Math.min(candidates[j], candidates[j - 1]);
}
}
}
int ans = candidates[0];
for (int i = 1; i < candidates.length; ++i) {
if (candidates[i] < ans) {
ans = candidates[i];
}
}
return ans;
}
}