Brush title LintCode - Digital triangle

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/kingslave1/article/details/78179463

description:

Given a digital triangle, from the smallest to find a path in the end portion and the top. Each step can be shifted onto the adjacent lower row numbers.

Sample

For example, the following figures are given triangle:

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

Minimum path from the top in the end portion 11 and a (2 + 3 + 5 + 1 = 11).



public class Solution {
    /*
     * @param triangle: a list of lists of integers
     * @return: An integer, minimum path sum
     */
    public int minimumTotal(int[][] triangle) {
        if(triangle==null||triangle.length==0)
        	return 0;
        
		int [][]dp=new int[triangle.length][];
        dp[0]=new int[1];
        dp[0][0]=triangle[0][0];
        
        int cols=0;
        int currentMin=dp[0][0];
        
        for(int i=1;i<triangle.length;i++) {
        	cols=triangle[i].length;
        	dp[i]=new int[cols];
        	dp[i][0]=dp[i-1][0]+triangle[i][0];
        	currentMin=dp[i][0];
        	for(int j=1;j<cols-1;j++) {
        		dp[i][j]=Integer.min(dp[i-1][j-1], dp[i-1][j])+triangle[i][j];
        		if(currentMin>dp[i][j]) {
        			currentMin=dp[i][j];
        		}
        	}
        	dp[i][cols-1]=dp[i-1][cols-2]+triangle[i][cols-1];
        	if(currentMin>dp[i][cols-1]) {
    			currentMin=dp[i][cols-1];
    		}
        }
        return currentMin;
	}
}


Guess you like

Origin blog.csdn.net/kingslave1/article/details/78179463