zoukankan      html  css  js  c++  java
  • 【题解】【矩阵】【回溯】【Leetcode】Unique Paths II

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    How many possible unique paths are there?

    NewImage

    Above is a 3 x 7 grid. How many possible unique paths are there?

    Now consider if some obstacles are added to the grids. How many unique paths would there be?

    An obstacle and empty space is marked as 1 and 0 respectively in the grid.

    For example,

    There is one obstacle in the middle of a 3x3 grid as illustrated below.

    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    

    The total number of unique paths is 2.

    Note: m and n will be at most 100.

    思路:

    很典型的回溯问题,到[i,j]的路径等于到[i-1,j]和[i,j-1]的路径之和,然后为了避免重复求解子问题,结合查表法记录子问题结果。编码要点在于处理 trivial case。

    代码:

     1 int uniquePaths2Node(vector<vector<int> > &oGrid, vector<vector<int> > &paths, int i, int j){
     2     //if(i < 0 || j < 0) return 0;//failed [[1]]=>0, 应该把控制条件放下面,不给调用不valid的子问题
     3     if(oGrid[i][j] == 1) return 0;
     4     
     5     if(i == 0 && j == 0) return 1 ^ oGrid[0][0];//failed [[0]]=>1
     6 
     7     int P = 0;
     8     if(i > 0 && oGrid[i-1][j] != 1){
     9         if(paths[i-1][j] == -1)
    10             paths[i-1][j] = uniquePaths2Node(oGrid, paths, i-1, j);
    11         P += paths[i-1][j];
    12     }
    13     if(j > 0 && oGrid[i][j-1] != 1){
    14         if(paths[i][j-1] == -1)
    15             paths[i][j-1] = uniquePaths2Node(oGrid, paths, i, j-1);
    16         P += paths[i][j-1];
    17     }
    18     return P;
    19 }
    20 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
    21     int m = obstacleGrid.size();
    22     if(m == 0) return 0;
    23     int n = obstacleGrid[0].size();
    24     if(n == 0) return 0;
    25 
    26     vector<vector<int> > paths(m, vector<int>(n, -1));
    27     return uniquePaths2Node(obstacleGrid, paths, m-1, n-1);
    28 }
  • 相关阅读:
    配置动态刷新RefreshScope注解使用局限性(一)
    OAuth2 Token 一定要放在请求头中吗?
    Spring Boot 2.3 新特配置文件属性跟踪
    为什么 Spring Boot 2.3.0 放弃Maven最终拥抱Gradle
    Spring Boot 2.3.0 新特性Redis 拓扑动态感应
    【spring cloud hoxton】Ribbon 真的能被 spring-cloud-loadbalancer 替代吗
    Spring Cloud Gateway 扩展支持动态限流
    聊聊 OAuth 2.0 的 token expire_in 使用
    「starter推荐」简单高效Excel 导出工具
    用mint-ui tabber写餐厅分层
  • 原文地址:https://www.cnblogs.com/wei-li/p/UniquePathsII.html
Copyright © 2011-2022 走看看