-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
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.
要注意的是:
- 三角形数组的创建(C++用vector方便多了)
- 要按照题目所给的三角形递归路线。
class Solution {
// stupid problem!!!!!
// 三角形是按照题目图示所给的三角形
public int minimumTotal(List<List<Integer>> triangle) {
int m = triangle.size();
if (m == 0) {
return 0;
}
if (m == 1) {
return triangle.get(0).get(0);
}
int[][] dp = new int[m][];
int i = 0, j = 0;
for (i = 0; i < m; ++i) {
dp[i] = new int[i + 1];
}
dp[0][0] = triangle.get(0).get(0);
for (i = 1; i < m; ++i) {
for (j = 0; j <= i; ++j) {
if (j == 0) {
dp[i][j] = dp[i - 1][j];
}
else if (j == i) {
dp[i][j] = dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]);
}
dp[i][j] += triangle.get(i).get(j);
}
}
int res = Integer.MAX_VALUE;
for (j = 0; j < m; ++j) {
res = Math.min(res, dp[m - 1][j]);
}
return res;
}
}class Solution {
// spcae:O(n)
// Warning:三角形是按照题目图示所给的三角形
public int minimumTotal(List<List<Integer>> triangle) {
int m = triangle.size();
if (m == 0) {
return 0;
}
if (m == 1) {
return triangle.get(0).get(0);
}
int[] dp = new int[m + 1];
int i = 0, j = 0;
dp[0] = triangle.get(0).get(0);
int pre = dp[0];
for (i = 1; i < m; ++i) {
for (j = 0; j <= i; ++j) {
if (j == 0) {
pre = dp[j];
}
else if (j == i) {
dp[j] = pre;
}
else {
int old = dp[j];
dp[j] = Math.min(dp[j], pre);
pre = old;
}
dp[j] += triangle.get(i).get(j);
}
}
int res = Integer.MAX_VALUE;
for (j = 0; j < m; ++j) {
res = Math.min(res, dp[j]);
}
return res;
}
}参考资料:
LeetCode原题
Metadata
Metadata
Assignees
Labels
No labels