zoukankan      html  css  js  c++  java
  • [LeetCode]20. 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.

    解法:还是使用动态规划。不同的是若遇到障碍,则说明到此位置后面就行不通了,路径数目为0。注意初始化不能再是path[i][0]=1,path[0][j]=1(0<=i<m,0<=j<n),而是path[0][0]=1,因为第一行和第一列上就有可能有障碍。

    class Solution {
    public:
        int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
            int res = 0;
            if(obstacleGrid.empty() || obstacleGrid[0].empty())
                return res;
            int m = obstacleGrid.size();
            int n = obstacleGrid[0].size();
    
            vector<int> path(n, 0);
            path[0] = 1;
            for(int i = 0; i < m; i++)
            {
                for(int j = 0; j < n; j++)
                {
                    if(obstacleGrid[i][j] == 1)
                        path[j] = 0;
                    else if(j > 0)
                        path[j] += path[j - 1];
                }
            }
            
            res = path[n - 1];
            return res;
        }
    };
  • 相关阅读:
    redis配置引发的问题
    String类的split()方法
    修改mysql编码配置文件不生效
    mysql性能优化小知识点
    limit使用
    mysql执行顺序
    记录一个不知名的错误
    子数组最大和及下标
    maven项目中不能加载java目录下的配置文件
    判断树是否为搜索树
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4865204.html
Copyright © 2011-2022 走看看