https://oj.leetcode.com/problems/triangle/
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.
下面依次爲參考源代碼:法一採用JAVA(採用不修改原數組元素),法二採用C++(修改原數組元素值)。
public int minimumTotal(List<List<Integer>> triangle) {
//We record each minimum sum value for each index in the triangle.
//We compute these values from top to bottom.
List<List<Integer>> ixSum = new ArrayList<>(triangle.size());
for (int i = 0; i < triangle.size(); ++i) {
List<Integer> lines = triangle.get(i);
ixSum.add(new ArrayList<Integer>(lines.size()));
if (i == 0) {
ixSum.get(0).add(lines.get(0)); //Notice that, we use 'add' method rather than 'set' method.
} else {
for (int j = 0; j < lines.size(); ++j) {
if (j == 0) {
ixSum.get(i).add((ixSum.get(i - 1).get(0) + lines.get(0)));
} else if (j == (lines.size() - 1)) {
// Notice that: ixSum.get(i).get(j-1).
ixSum.get(i).add((ixSum.get(i - 1).get(j - 1) + lines.get(j)));
} else {
if (ixSum.get(i - 1).get(j) > ixSum.get(i - 1).get(j - 1)) {
ixSum.get(i).add(ixSum.get(i - 1).get(j - 1) + lines.get(j));
} else {
ixSum.get(i).add(ixSum.get(i - 1).get(j) + lines.get(j));
}
}
}
}
}
int min = Integer.MAX_VALUE;
for (int e : ixSum.get(ixSum.size()-1)) {
if (e < min) {
min = e;
}
}
ixSum = null;
return min;
}
法二: C++代碼(修改原數組元素):
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
for (int i = triangle.size() - 2; i >= 0; --i)
for (int j = 0; j < i + 1; ++j){
if(triangle[i+1][j] > triangle[i+1][j+1]){
triangle[i][j] += triangle[i+1][j+1];
}else{
triangle[i][j] += triangle[i+1][j];
}
}
return triangle[0][0];
}
};