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 is11(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.
思路:可以發現第l排的第k個元素的下一排只可能是第l+1排的第k個元素或者是第l+1排的第k+1個元素。遞歸即可實現
代碼:
import java.util.ArrayList; public class Solution { public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { int sum; sum = Result(triangle,0,0); return sum; } public int Result(ArrayList<ArrayList<Integer>> triangle,int l ,int k){ int sum = triangle.get(l).get(k); if(l<triangle.size()-1){ sum = sum+Math.min(Result(triangle,l+1,k),Result(triangle,l+1,k+1)); } return sum; } }