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.
思路:记录最后一行sum,然后求出最小值
注意事项:由于下一行比上一行多一个值,所以要从后向前覆盖
java代码:
- public int minimumTotal(List<List<Integer>> triangle) {
- if(triangle==null) return 0;
- int high = triangle.size();
- if(high==0) return 0;
- int[] result = new int[high];
- int final_value = Integer.MAX_VALUE;
- for(int i=0;i<high;i++) {
- int j=0;
- List<Integer> line = triangle.get(i);
- for(j=line.size()-1;j>=0;j--) {
- if(i==0) {
- result[j] =line.get(j);
- } else {
- if(j==0) result[0] = result[0] + line.get(0);
- else if(j==line.size()-1) {
- result[j] = result[j-1] + line.get(j);
- }
- else {
- if(result[j-1] > result[j])
- result[j] = result[j] + line.get(j);
- else
- result[j] = result[j-1] + line.get(j);
- }
- }
- if(i==high-1) {
- if(result[j] < final_value) {
- final_value = result[j];
- }
- }
- }
- }
- return final_value;
- }
C++代码: 从后向前
- int minimumTotal(vector<vector<int> > &triangle) {
- if(triangle.empty()) return 0;
- vector<int> flag;
- int high = triangle.size();
- flag.resize(triangle[high-1].size());
- for(int i=high-1;i>=0;i--) {
- int width = triangle[i].size();
- for(int j=0;j<width;j++) {
- if(i==high-1) flag[j] = triangle[i][j];
- else flag[j] = triangle[i][j] + min(flag[j],flag[j+1]);
- }
- }
- return flag[0];
- }

浙公网安备 33010602011771号