Triangle

LeetCode Q 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.

Solution : DP

We build the path from bottom to top.
State Transfer Function:
dp[j] = Math.min(dp[j], dp[j + 1]) + list.get(j);

Code: Use Array

public int minimumTotal(List<List<Integer>> triangle) {
	if (triangle == null) return 0;
	int[] dp = new int[triangle.size()];
	for (int i = 0; i < dp.length; i++) 
		dp[i] = triangle.get(triangle.size() - 1).get(i);
	
	for (int i = triangle.size() - 2; i >= 0; i--) {
		List<Integer> list = triangle.get(i);
		for (int j = 0; j < list.size(); j++)
			dp[j] = Math.min(dp[j], dp[j + 1]) + list.get(j);
	}
	
	return dp[0];
}

Code: Use ArrayList

public int minimumTotal(List<List<Integer>> triangle) {
	int n = triangle.size();
	List<Integer> list = new ArrayList<>(triangle.get(n-1));
	for (int i = n - 2; i >= 0; i--) {
		for (int j = 0; j <= i; j++) {
			list.set(j, triangle.get(i).get(j) + Math.min(list.get(j), list.get(j + 1)));
		}
	}
	return list.get(0);
}

   Reprint policy


《Triangle》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC