动态规划最短路径LintcodeNO110

动态规划最短路径LintcodeNO110

简单的dp题,没啥好说的...

class Solution {
public:
    /**
     * @param grid: a list of lists of integers
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    int minPathSum(vector<vector<int>> &grid) {
        
        // write your code here
        const int DP_N = 1000;
        const int DP_M = 1000;
        int n = grid.size();
        int m = grid[0].size();
        int i,j;
        int dp[DP_N][DP_M];
        memset(dp,0,DP_N * DP_M);
        //初始化dp数组的值
        dp[0][0] = grid[0][0];
        for(int t=1;t<n;t++)
        {
            dp[t][0] = dp[t-1][0] + grid[t][0];
        }
        for(int k=1;k<m;k++)
        {
            dp[0][k] = dp[0][k-1] + grid[0][k];
        }
    	
        //开始dp
        for(i=1;i<n;i++)
        {
            for(j=1;j<m;j++)
            {
               dp[i][j] = grid[i][j] + min(dp[i-1][j],dp[i][j-1]);
            }
        }

        return dp[i-1][j-1];

    }
};

在本地调试代码的时候遇到 int dp[DP_N][DP_M]; 行列都大于1000时分配失败的问题.

解决,本地调试调小一点,Submit时再调回来就好了

注意一下边界问题,还有记得初始化dp数组.

posted @ 2019-11-12 22:01  virgil_devil  阅读(115)  评论(0编辑  收藏  举报