LeetCode(Minimum Path Sum) 找到路径中和最小的

题目要求:

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.

思路: 可以用深度搜索,但是会超时, 所以只能用动态规划。

代码:

class Solution {
public:
  int min_res;
  int minPathSum(vector > &grid) 
  {
//    int row = grid.size();
//    int col = grid[0].size();
//    int direction[4][2] = 
//    {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
//    vector visited(row * col, false);
//    min_res = 1 << 30;
//    DFS(grid, visited, direction, 0, 0, row, col, 0);
    return DP(grid);
  }
  
  int DP(vector >& grid)
  {
    int row = grid.size();
    int col = grid[0].size();
    int dp[row][col];
    dp[0][0] = grid[0][0];
    for(size_t i = 1; i < row; ++i)
      dp[i][0] = dp[i - 1][0] + grid[i][0];
    for(size_t i = 1; i < col; ++i)
      dp[0][i] = dp[0][i - 1] + grid[0][i];
    for(size_t i = 1; i < row; ++i)
      for(size_t j = 1; j < col; ++j)
      {
        dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
      }
    return dp[row - 1][col - 1];
  }
  
  void DFS(vector >& grid, vector& visited, int dir[4][2],
          int row, int col, 
          int heigh, int width, int sum)
  {
    sum += grid[row][col];
    if(row == heigh - 1 && col == width - 1)
    {
      if(sum < min_res)
        min_res = sum;
      return; 
    }
    
    visited[row * width + col] = true;
    for(size_t i = 0; i < 4; ++i)
    {
      int new_row = row + dir[i][0];
      int new_col = col + dir[i][1];
      if(new_row >= 0 && new_row < heigh && 
         new_col >= 0 && new_col < width && !visited[new_row * width + new_col])
        DFS(grid, visited, dir, new_row, new_col, heigh, width, 
            sum);
    }
    visited[row * width + col] = false;
  }
};


你可能感兴趣的:(c++,LeetCode,面试题,面试,leetcode,dfs,dp)