[120] C language brush LeetCode triangular path and the minimum (M)

Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes.

For example, given triangle:

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


Top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/triangle
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

This question is the classic dynamic programming problem, we saw many times.

Recursive idea is from the bottom up, recursive formula: dp [i] [j] = tmp + triangle [i] [j]; tmp = MIN (dp [i + 1] [j], dp [i + 1 ] [j + 1]);

#define MIN(a, b) (a) > (b) ? (b) :(a)

int minimumTotal(int** triangle, int triangleSize, int* triangleColSize){
    int i;
    int j;
    int dp[triangleSize][triangleSize];
    int tmp = 0;
    
    //printf("triangleSize=%d,*triangleColSize=%d\n", triangleSize, *triangleColSize);
    
    memset(dp, 0, sizeof(int) * triangleSize * triangleSize);
    
    if(triangleSize == 1) return triangle[0][0];
    
    for(j = 0; j < triangleSize; j++) {
        dp[triangleSize -1][j] = triangle[triangleSize -1][j];
    }
    
    for(i = triangleSize -2; i >= 0; i--) {
        for(j = 0; j <= i; j++) {
            tmp = MIN(dp[i+1][j], dp[i+1][j+1]);
            dp[i][j] = tmp + triangle[i][j];
            
            //printf("dp[%d][%d]=%d, triangle=%d,tmp=%d\n", i, j, dp[i][j], triangle[i][j],tmp);
        }
    }
    
    return dp[0][0];
}

 

Published 110 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/jin615567975/article/details/104330236