本文介绍: 【代码】LeetCode //C – 64. Minimum Path Sum

64. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.
 

Example 1:

在这里插入图片描述

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

Constraints:

From: LeetCode
Link: 64. Minimum Path Sum


Solution:

Ideas

This function assumes that the memory for grid has already been allocated and that gridSize and gridColSize are correctly set to reflect the dimensions of grid. The min function is a helper to find the minimum of two numbers.

The function calculates the minimum path sum in a bottom-up manner, filling in the dp table from the topleft to the bottom-right. After calculating the minimum path sum, it cleans up the allocated memory for dp and returns the result.

Code:
int minPathSum(int** grid, int gridSize, int* gridColSize) {
    // The gridSize is the number of rows, and gridColSize[0] is the number of columns.
    int i, j;
    
    // Allocate space for the dp matrix
    int **dp = (int **)malloc(gridSize * sizeof(int *));
    for(i = 0; i < gridSize; i++) {
        dp[i] = (int *)malloc(gridColSize[0] * sizeof(int));
    }
    
    // Initialize the top-left corner
    dp[0][0] = grid[0][0];
    
    // Fill the first row (only right moves are possible)
    for(j = 1; j < gridColSize[0]; j++) {
        dp[0][j] = dp[0][j - 1] + grid[0][j];
    }
    
    // Fill the first column (only down moves are possible)
    for(i = 1; i < gridSize; i++) {
        dp[i][0] = dp[i - 1][0] + grid[i][0];
    }
    
    // Fill the rest of the dp matrix
    for(i = 1; i < gridSize; i++) {
        for(j = 1; j < gridColSize[0]; j++) {
            dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    
    // The bottom-right corner has the result
    int result = dp[gridSize - 1][gridColSize[0] - 1];
    
    // Free the dp matrix
    for(i = 0; i < gridSize; i++) {
        free(dp[i]);
    }
    free(dp);
    
    return result;
}

// Helper function to find the minimum of two numbers
int min(int a, int b) {
    return (a < b) ? a : b;
}

原文地址:https://blog.csdn.net/navicheung/article/details/134694559

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_30822.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注