dfs最后两组数组超时过不了,只能用动态规划
dp:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int r = grid.size(),c = grid[0].size();
vector<vector<int>> dp(r, vector<int>(c));
for(int i = 0;i < r;i++){
for(int j = 0;j < c;j++){
if(i==0 && j==0)
dp[0][0] = grid[0][0];
else if(i==0)
dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j==0)
dp[i][j] = dp[i-1][j] + grid[i][j];
else
{
if(dp[i][j-1]+grid[i][j] < dp[i-1][j]+grid[i][j])
dp[i][j] = dp[i][j-1]+grid[i][j];
else
dp[i][j] = dp[i-1][j]+grid[i][j];
}
}
}
return dp[r-1][c-1];
}
};
dfs:
class Solution {
public:
vector<vector<int>> grid1;
int Min = INT_MAX;
int minPathSum(vector<vector<int>>& grid) {
grid1 = grid;
int r = grid.size(),c = grid[0].size();
vector<vector<int>> vis(r, vector<int>(c));
dfs(vis,r-1,c-1,0,0,0);
return Min;
}
void dfs(vector<vector<int>>& vis,int m,int n,int i,int j,int sum){
if(sum >= Min)
return;
if(i == m && j == n)
{
if(sum+grid1[i][j]<Min)
Min=sum+grid1[i][j];
return;
}
if(i == m)
return dfs(vis,m,n,i,j+1,sum+grid1[i][j]);
if(j == n)
return dfs(vis,m,n,i+1,j,sum+grid1[i][j]);
dfs(vis,m,n,i+1,j,sum+grid1[i][j]);
dfs(vis,m,n,i,j+1,sum+grid1[i][j]);
return;
}
};