mio4 Java Web & Web Security

【LeetCode题解】 120. Triangle(Java)

2018-10-19
mio4

阅读:


(一)120. 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.

  • 自底向上,从倒数第二行开始
    • 每个元素 = 当前元素 + min(下一行相邻第一个元素,下一行相邻第二个元素)
    • 遍历之后,第一行第一个元素就是结果
  • 最优子结构:F[i][j] = F[i][j] + min(F[i+1][j],F[i+1][j+1])
package DynamicProgramming.Triangle;

import java.util.ArrayList;

public class Solution {

	public static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
		int size = triangle.size(); //三角形的行数
		for(int i= size - 2; i >= 0; i--){
			for(int j=0; j <= i; j++){
				triangle.get(i).set(j,triangle.get(i).get(j) + Math.min(triangle.get(i+1).get(j),triangle.get(i+1).get(j+1)));
			}
		}
		return triangle.get(0).get(0);
	}

	public static void main(String[] args){
		ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>();
		ArrayList<Integer> l1 = new ArrayList<Integer>();
		ArrayList<Integer> l2 = new ArrayList<Integer>();
		ArrayList<Integer> l3 = new ArrayList<Integer>();
		ArrayList<Integer> l4 = new ArrayList<Integer>();
		l1.add(2);

		l2.add(3);
		l2.add(4);

		l3.add(6);
		l3.add(5);
		l3.add(7);

		l4.add(4);
		l4.add(1);
		l4.add(8);
		l4.add(3);

		triangle.add(l1);
		triangle.add(l2);
		triangle.add(l3);
		triangle.add(l4);
		System.out.println(minimumTotal(triangle));
	}
}


Comments

Content