We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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.
要注意的是:
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原题
The text was updated successfully, but these errors were encountered:
No branches or pull requests
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
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.
要注意的是:
参考资料:
LeetCode原题
The text was updated successfully, but these errors were encountered: