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];
}

20 thoughts on “LeetCode – Triangle (Java)”

  1. solution 2 !!!!!!!!!

    no need n extra space!!

    just use recursive function
    1
    56
    789
    4563

    for each string , for each element call itself w/ element index , and index+1
    have common (ref) variable,keep minimal sum!!!!!!

  2. solution 1

    can use tree solution. ! just tranform into tree structure

    3 4

    6 5 7

    into node left 6 , root 3 , right 5 and 5 left , 4 root , right 7

    then its just matter of in order traverse, for each node that dont have any child aka end of path, take sum
    compare to previous saved (or negative if 1st time), take minimal of

    and so on…


  3. var x = [
    [2],
    [3,4],
    [6,5,7],
    [4,1,8,3]
    ]
    var sum = 0;
    var j = 0;
    for(var i = 0; i = 0 && j+1 = 0)
    ? x[i][j-1]
    : (j+1 < x[i].length)
    ? x[i][j+1]
    : x[i][j]
    val = Math.min( small ,x[i][j] )
    }
    j = x[i].indexOf(val)
    console.log(val)
    sum += val;
    }
    console.log(sum)

  4. o(1);

    public class Triangle {

    public int findMinimumPath(final int[][] array) {
    if (array.length > 1) {
    for (int i = array.length - 1; i >= 0; i--) {
    for (int j = 0; j < array[i].length - 1; j++) {
    array[i - 1][j] += Math.min(array[i][j], array[i][j + 1]);
    }
    }
    }
    return array[0][0];
    }
    }

  5. 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));

    }

  6. 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);
    }

  7. 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;
    }

  8. 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;
    }

  9. 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)! 🙂

  10. 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.

  11. 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;
    }

  12. /** 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;
    }
    }

  13. 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;
    }
    }

  14. 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…

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

  16. 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()];

  17. 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

  18. 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)

Leave a Comment