304 North Cardinal St.
Dorchester Center, MA 02124

# Triangle LeetCode Solution

## Problem – Triangle LeetCode Solution

Given a `triangle` array, return the minimum path sum from top to bottom.

For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.

Example 1:

``````Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
``````

Example 2:

``````Input: triangle = [[-10]]
Output: -10
``````

Constraints:

• `1 <= triangle.length <= 200`
• `triangle[0].length == 1`
• `triangle[i].length == triangle[i - 1].length + 1`
• `-104 <= triangle[i][j] <= 104`

Follow up: Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?

## Triangle LeetCode Solution in Java

``````public int minimumTotal(List<List<Integer>> triangle) {
int[] A = new int[triangle.size()+1];
for(int i=triangle.size()-1;i>=0;i--){
for(int j=0;j<triangle.get(i).size();j++){
A[j] = Math.min(A[j],A[j+1])+triangle.get(i).get(j);
}
}
return A[0];
}
``````

## Triangle LeetCode Solution in C++

``````class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle)
{
vector<int> mini = triangle[triangle.size()-1];
for ( int i = triangle.size() - 2; i>= 0 ; --i )
for ( int j = 0; j < triangle[i].size() ; ++ j )
mini[j] = triangle[i][j] + min(mini[j],mini[j+1]);
return mini[0];
}
};
``````

## Triangle LeetCode Solution in Python

``````def minimumTotal(self, triangle):
f = [0] * (len(triangle) + 1)
for row in triangle[::-1]:
for i in xrange(len(row)):
f[i] = row[i] + min(f[i], f[i + 1])
return f[0]]
``````
##### Triangle LeetCode Solution Review:

In our experience, we suggest you solve this Triangle LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Triangle LeetCode Solution

Find on Leetcode

##### Conclusion:

I hope this Triangle LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions