Leetcode - Dynamic Progr - 64. Minimum Path Sum(BFS+DP)

1. Problem Description

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.

 

给出一个m*n的矩阵,每个矩阵里有一个值,求从左上角走到右下角经过和最小的路径,输出最小和。

Note:你只可以走右边或者下边。

 

2. My solution1 BFS(TLE)

先用BFS写的,每次走到一个节点都要把其邻近节点扫一下,复杂度是节点数*2,也就是O[n*m*2]

结果TLE了……

class Solution
{
private :
    int dir[2][2];
    int row;
    int col;
public:
 
    typedef struct
    {
        int i;
        int j;
        int val;
    } Node;
    bool judge(Node tmp)
    {
        if(tmp.i>=0&&tmp.i=0&&tmp.j >& grid)
    {
        queueque;
        Node q0= {0,0,grid[0][0]};
        que.push(q0);
        int ans=(1<<30)-1;
        while(!que.empty())
        {
            Node ff=que.front();
            que.pop();
 
            if(ff.i==row-1&&ff.j==col-1)
            {
                if(ff.val >& grid)
    {
        dir[0][0]= 1,dir[0][1]= 0;
        dir[1][0]= 0,dir[1][1]= 1;
        row=grid.size();
 
        if(row==0)
            return 0;
        col=grid[0].size();
        return BFS(grid);
    }
};


3. My solution2 Dp(AC)

果然还是要DP啊,这个题的DP很好搞,就是dp[i][j]=min(dp[i-1][j],dp[i][j-1]);

因为只能向下或者向右走,O[m*n]的复杂度。

class Solution
{
private:
    int dir[2][2];
    int row;
    int col;
    vector >dp;
public:
    bool judge(int i,int j)
    {
        if(i>=0&&i=0&&j >& grid)
    {
        for(int i=0; i >& grid)
    {
        row=grid.size();
        if(row==0)
            return 0;
        col=grid[0].size();
        for(int i=0; itmp;
            dp.push_back(tmp);
            for(int j=0; j


你可能感兴趣的:(leetcode)