LeetCode – Triangle (Java)

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.

Bottom-Up (Good Solution)

We can actually start from the bottom of the triangle.

public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
	int[] total = new int[triangle.size()];
	int l = triangle.size() - 1;
 
	for (int i = 0; i < triangle.get(l).size(); i++) {
		total[i] = triangle.get(l).get(i);
	}
 
	// iterate from last second row
	for (int i = triangle.size() - 2; i >= 0; i--) {
		for (int j = 0; j < triangle.get(i + 1).size() - 1; j++) {
			total[j] = triangle.get(i).get(j) + Math.min(total[j], total[j + 1]);
		}
	}
 
	return total[0];
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Jie on 2014-5-10

    public class Solution {

    public int minimumTotal(ArrayList<ArrayList> triangle) {

    int height = triangle.size();

    for (int i=height-2; i>=0; i–){

    for (int j=0; j<i+1; j++){

    ArrayList current = triangle.get(i);

    ArrayList next = triangle.get(i+1);

    current.set(j, current.get(j) + Math.min(next.get(j), next.get(j+1)));

    }

    }

    return triangle.get(0).get(0);

    }

    }

    you can make space to O(1)

  2. df on 2014-5-28

    python solution

    def min_path_sum(arr):

    min_sum = 0
    for i in range(len(arr)):
    print (‘+’ ,min(arr[i]))
    min_sum += min(arr[i])
    return min_sum

  3. Lucy on 2014-7-1

    Hi,

    I think second line of second solution is not right. You use total to record every path’s cost in one layer right?

    So the first two lines should be:

    int l = triangle.size() – 1;

    int[] total = new int[triangle.get(l).size()];

  4. Sureshkumar T on 2014-11-12

    We can use a treeSet to store the elements of each row so we can solve the problem with complexity of O(n).

  5. iberras on 2014-11-17

    This doesn’t work with the adjacent condition. It’s a smart move, but if you order he items, then you could pick one that is not adjacent…

  6. Sureshkumar T on 2014-11-18

    Thanks for pointing the mistake probably i have overlooked the question. Here is the solution with complexity of O(n)

    public static int minimumAdjacentTotal(List<List> triangle) {
    if (triangle.size() <= 0) {
    return 0;
    } else {
    int sum = 0;
    int pos = 0;
    for (List row : triangle) {
    if(row.size()>1) {
    if(row.get(pos) < row.get(pos + 1)) {
    sum += row.get(pos);
    } else {
    sum += row.get(pos+1);
    pos++;
    }
    } else {
    sum += row.get(pos);
    }
    }
    return sum;
    }
    }

  7. Adil qureshi on 2015-6-19

    /** Very Easy & Working.

    Class Solution {
    public int doSum(ArrayList<ArrayList> inputList) {
    int sum = 0;

    for (ArrayList list : inputList) {
    int minimun = Integer.MAX_VALUE;
    for (Integer num : list) {
    int tempMin = Math.min(num, minimun);
    minimun = tempMin;
    }
    sum = sum + minimun;

    }

    return sum;
    }
    }

  8. up23 on 2015-8-23

    In php or any language using a min() function, it’s simple:

    function minTotal( array $rows) {
    $bestAns = 0;

    for ($i = 0; $i < count($rows); $i ++) {
    $bestAns += min($rows[$i]);
    }

    return $bestAns;
    }

  9. lthuongvn on 2015-11-12

    Can we solve this problem by finding the minimum value at each row. Then the path from top to bottom would be the root, min of 1st row, min of 2nd row,,., min of last row.

  10. Candis on 2015-11-21

    The first solution could have been right had we created another array and stored there and then copied it back to temp.! The space was still O(N)! 🙂

  11. kUkaraCH4 on 2015-11-22

    This solution uses O(n) extra space. You can technically use O(1) space, given that modification of the original triangle is allowed, by storing the partial minimum sum of the current value and the smaller of its lower neighbors. If we need to restore the original triangle we can then do it in a separate method which does use O(n) extra space but is only called lazily when needed:

    public int minimumTotal(ArrayList<ArrayList> a) {
    if (a == null || a.size() == 0) return -1;
    if (a.size() == 1) return a.get(0).get(0);
    for (int i = a.size() - 2; i >= 0; i--) {
    ArrayList low = a.get(i);
    ArrayList high = a.get(i+1);
    for (int j = 0; j i).toArray();
    for (int i = a.size() - 2; i >= 0; i--) {
    ArrayList curr = a.get(i);
    for (int j = 0; j < curr.size(); j++) {
    int sum = curr.get(j);
    curr.set(j, curr.get(j) - Math.min(mem[j], mem[j+1]));
    mem[j] = sum;
    }
    }
    return res;
    }

  12. Piyush Chaudhary on 2016-2-8

    Wrong solution. Won’t work for : [[-1],[2,3],[1,-1,-3]]

  13. Surabhi Dixit on 2016-7-25

    Anything wrong with my solution?

    public static int addinput(int[][]x)
    {
    int i=0,j=0,sum=0,previous=0;
    while(i1&&j!=1)
    j=1;

    }
    return sum;
    }

  14. Rudolf Eremyan on 2016-9-21

    Without using Extra Space, just modified existing ArrayLists

    public static int findMinPath(ArrayList<ArrayList> lists) {

    if(lists.size() == 1){
    return lists.get(0).get(0);
    }

    for(int i = lists.size()-2; i >= 0; i–){
    int size = lists.get(i).size();

    for(int j = 0; j < size; j++){
    int min = Math.min( (lists.get(i).get(j) + lists.get(i+1).get(j)), (lists.get(i).get(j) + lists.get(i+1).get(j+1)) );
    lists.get(i).set(j, min);
    }
    }

    return lists.get(0).get(0);
    }

  15. Mayank Mittal on 2017-4-6

    By Recursion : I am considering input as an array

    int [][] arr = {{2,0,0,0},
    {3,4,0,0},
    {6,5,7,0},
    {4,1,8,3}
    };

    private int findMinSum(int[][] arr) {
    return findMinSum(arr,0,0,0);

    }
    private int findMinSum(int[][] arr, int row, int col,int sum) {
    if(row > arr.length-1 || col > arr.length-1){
    return 0;
    }
    sum = arr[row][col];
    return sum + Math.min(findMinSum(arr,row+1,col,sum),findMinSum(arr,row+1,col+1,sum));

    }

Leave a comment

*