码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Minimum Path Sum

时间:2015-04-14 21:34:01      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目:
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.

思路分析:
我们只要保证当前的第k歩是最小的,然后第k+1歩同样选择最小的,这样走下去就OK了。
递推公式:path[i][j] = min(path[i-1][j], path[j][i-1]) + path[i][j]

先看一个4*4的方格,0表示初始位置,i表示第i歩可以走的位置。大概了解下该怎么走。

0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6

C++参考代码:
先对首行和首列进行初始化,然后利用递推公式进行计算。

class Solution
{
public:
    int minPathSum(vector<vector<int> > &grid)
    {
        if (grid.empty() || grid[0].empty()) return 0;

        int rows = int(grid.size());
        int columns = int(grid[0].size());

        //二维数组的动态申请
        int **result = new int*[rows];
        for (int i = 0; i < rows; ++i)
        {
            result[i] = new int[columns];
        }
        result[0][0] = grid[0][0];

        //第一列进行初始化
        for (int i = 1; i < rows; ++i)
        {
            result[i][0] = result[i - 1][0] + grid[i][0];
        }

        //第一行进行初始化
        for (int i = 1; i < columns; ++i)
        {
            result[0][i] = result[0][i - 1] + grid[0][i];
        }

        //利用递推公式进行计算
        for (int i = 1; i < rows; ++i)
        {
            for (int j = 1; j < columns; ++j)
            {
                result[i][j] = min(result[i - 1][j], result[i][j - 1]) + grid[i][j];
            }
        }

        int sum = result[rows - 1][columns - 1];
        //申请空间的释放
        for (int i = 0; i < rows; ++i)
        {
            delete[] result[i];
        }
        delete[] result;
        return sum;
    }
};

C#参考代码:
虽然没有C++的高效,但是C#代码书写有时候感觉很优雅,简洁明了!

public class Solution
{
    public int MinPathSum(int[,] grid)
    {
        if (grid.Length == 0) return 0;
        //获得二维数组的行数
        int rows = grid.GetLength(0);
        //获得二维数组的列数
        int columns = grid.GetLength(1);
        int[,] result = new int[rows, columns];
        result[0, 0] = grid[0, 0];
        for (int i = 1; i < rows; ++i)
        {
            result[i, 0] = result[i - 1, 0] + grid[i, 0];
        }
        for (int i = 1; i < columns; ++i)
        {
            result[0, i] = result[0, i - 1] + grid[0, i];
        }
        for (int i = 1; i < rows; i++)
        {
            for (int j = 1; j < columns; j++)
            {
                result[i, j] = Math.Min(result[i - 1, j], result[i, j - 1]) + grid[i, j];
            }
        }
        return result[rows - 1, columns - 1];
    }
}

Leetcode: Minimum Path Sum

标签:leetcode

原文地址:http://blog.csdn.net/theonegis/article/details/45047489

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!