leetcode-64.最小路径和

1. 题目

leetcode-64.最小路径和_第1张图片

2. 解答

data[i][j]表示位置i,j的值
dp[i][j]表示i,j位置的路径最小值;
0. 如果i = 0, j = 0, dp[i][j] = data[i][j];

  1. 如果i = 0,j != 0,dp[i][j] = data[i][j] + dp[i][j -1];
  2. 如果i!= 0, j = 0,dp[i][j] = data[i][j] + dp[i -1][j];
  3. 其他情况:dp[i][j] = data[i][j] + min(dp[i-1][j], dp[i][j - 1])
#include 
#include 

int min(int a, int b)
{
    return a < b? a:b;
}

int solve(int **data, int m, int n) 
{

    int dp[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 && j == 0) {
                dp[i][j] = data[i][j];
            } else if (i == 0 && j!= 0) {
                dp[i][j] = data[i][j] + dp[i][j -1];
            } else if (i != 0 && j == 0) {
                dp[i][j] = data[i][j] + dp[i -1][j];
            } else {
                dp[i][j] = data[i][j] + min(dp[i][j -1], dp[i -1][j]);
            }
        }
    }

    return dp[m-1][n-1];
}

int main()
{
    int m,n;
    scanf("%d %d", &m, &n);

    int **data = malloc(sizeof(int *)*m);
    for (int i = 0; i < m; i++) {
        data[i] = malloc(sizeof(int)*n);
        for (int j = 0; j < n; j++)
            scanf("%d", &data[i][j]);
    }

    int result = solve(data, m, n);

    printf("result:%d\n", result);

    return 0;
}

运行:

G3-3579:~/data/source/leetcode$ gcc 64smallpath.c 
G3-3579:~/data/source/leetcode$ ./a.out 
3 3
1 3 1
1 5 1
4 2 1
result:7
G3-3579:~/data/source/leetcode$ ./a.out 
2 3
1 2 3
4 5 6
result:12

你可能感兴趣的:(编程题或面试题,leetcode,算法)