• *Unique paths II


    题目:

    Follow up for "Unique Paths":

    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.

    解法一:我的解法

     1     public int uniquePathsWithObstacles(int[][] obstacleGrid) 
     2     {
     3         int m=obstacleGrid.length;
     4         //if(m==0) return 1;
     5         int n=obstacleGrid[0].length;
     6         int [][] grids = new int [m+1][n+1];
     7         grids[m][n-1]=1;
     8         for(int i=m-1;i>=0;i--)
     9         {
    10             for (int j=n-1;j>=0;j--)
    11             {
    12                 grids[i][j]=(obstacleGrid[i][j]==1) ? 0:grids[i+1][j]+grids[i][j+1];
    13             }
    14         }
    15         
    16         return grids[0][0];
    17         
    18     }

    解法二:九章算法的解法

     1     public int uniquePathsWithObstacles(int[][] obstacleGrid) 
     2     {
     3         int m=obstacleGrid.length;
     4         //if(m==0) return 1;
     5         int n=obstacleGrid[0].length;
     6         int [][] grids = new int [m][n];
     7         for (int i = 0; i < m; i++) 
     8         {
     9             if (obstacleGrid[i][0] != 1) {
    10                 grids[i][0] = 1;
    11             } else {
    12                 //grids[i][0] = 0;
    13                 break;   //第一列!错过了就不会再回到第一列!只能往右边和下边走。
    14             }
    15         }
    16         
    17         for (int i = 0; i < n; i++) {
    18             if (obstacleGrid[0][i] != 1) {
    19                 grids[0][i] = 1; 
    20             } else {
    21                 //grids[0][i] = 0;
    22                 break;   //第一行!错过了就不会回到第一行。
    23             }
    24         }
    25         
    26         
    27         
    28         for(int i=1;i<m;i++)
    29         {
    30             for (int j=1;j<n;j++)
    31             {
    32                 grids[i][j]=(obstacleGrid[i][j]==1) ? 0:grids[i-1][j]+grids[i][j-1];
    33             }
    34         }
    35         
    36         return grids[m-1][n-1];
    37         
    38     }
  • 相关阅读:
    树形数据深度排序处理示例(递归法).sql
    12种JavaScript MVC框架之比较
    逐级汇总示例(用户定义函数法).sql
    名次查询的处理示例.sql
    实现删除指定结点及所有子节点的处理触发器.sql
    memcpy和memmove的区别
    据说是月薪2W的笔试题
    C++重点知识
    Java初学者需掌握的30个概念
    (转)微软面试题
  • 原文地址:https://www.cnblogs.com/hygeia/p/4831820.html
Copyright © 2020-2023  润新知