Table of Contents
Problem Description
source: https://leetcode.com/problems/triangle/description/
Triangle
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
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Solution { public int minimumTotal(List<List<Integer>> triangle) { int m = triangle.size(); int n = triangle.get(m-1).size(); int[][] memo = new int[m+1][n+1]; for(int[] p: memo){ Arrays.fill(p, -1); } return dfs(triangle, 0, 0, memo); } private int dfs(List<List<Integer>> triangle, int row, int col, int[][] memo){ if(row >= triangle.size()){ return 0; } if(memo[row][col]!=-1) return memo[row][col]; int min = Integer.MAX_VALUE; //either you can choose i min = Math.min(min, triangle.get(row).get(col) + dfs(triangle, row+1, col, memo)); //or you can choose i+1 index if(row!=0){ min = Math.min(min, triangle.get(row).get(col+1) + dfs(triangle, row+1, col+1, memo)); } memo[row][col] = min; return min; } } |
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] :rtype: int """ ln = len(triangle) for i in xrange(1,ln): l = len(triangle[i]) triangle[i][0] += triangle[i-1][0] j=0 for j in xrange(1,l-1): triangle[i][j] += min(triangle[i-1][j], triangle[i-1][j-1]) triangle[i][j+1] += triangle[i-1][j] return min(triangle[ln-1]) |