LeetCode 120:三角形最小路径和
三角形最小路径和
1 void trianglePrint(int** triangle, int triangleSize, int* triangleColSize){ 2 int i, j; 3 for (i=0; i<triangleSize; ++i){ 4 for (j=0; j<triangleColSize[i]; ++j){ 5 printf("%d ", triangle[i][j]); 6 } 7 printf("\n"); 8 } 9 return ; 10 } 11 12 int minimumTotal(int** triangle, int triangleSize, int* triangleColSize){ 13 #define MINIMUM(a, b) ((a)>(b)?(b):(a)) 14 #define MAXIMUM(a, b) ((a)<(b)?(b):(a)) 15 int **dp, i, j, k, ret=0, n; 16 if (triangleSize == 1) { 17 return triangle[0][0]; 18 } 19 dp = malloc(sizeof(int*) * triangleSize); 20 for (i=0; i<triangleSize; ++i){ 21 dp[i] = malloc(sizeof(int) * triangleColSize[i]); 22 memset(dp[i], 0, sizeof(int) * triangleColSize[i]); 23 } 24 25 dp[0][0] = triangle[0][0]; 26 dp[1][0] = triangle[1][0] + dp[0][0]; 27 dp[1][1] = triangle[1][1] + dp[0][0]; 28 //trianglePrint(dp, triangleSize, triangleColSize); 29 30 for(i=2; i<triangleSize; ++i) { 31 dp[i][0] = dp[i-1][0]+triangle[i][0]; 32 33 for (j=1; j<triangleColSize[i]-1; ++j){ 34 dp[i][j] = MINIMUM(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]; 35 } 36 37 dp[i][triangleColSize[i]-1] = dp[i-1][triangleColSize[i-1]-1] + triangle[i][triangleColSize[i]-1]; 38 } 39 //trianglePrint(dp, triangleSize, triangleColSize); 40 i = triangleSize - 1; 41 ret = dp[i][0]; 42 for (j = 1; j < triangleColSize[i]; ++j){ 43 ret = MINIMUM(ret, dp[i][j]); 44 } 45 46 //free 47 for (i=0; i<triangleSize; ++i) { 48 free(dp[i]); 49 } 50 free(dp); 51 return ret; 52 }