• Leetcode 63. Unique Paths II


    63. Unique Paths II

    • Total Accepted: 70691
    • Total Submissions:237311
    • Difficulty: Medium

    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.

    思路:
    关于存储空间的优化,可以看姐妹题:Leetcode 62. Unique Paths

    0<=i<m,0<=j<n:

    1. obstacleGrid[i][j]==1,则(i,j)的路径数=0

    2. obstacleGrid[i][j]==0时

    2.1 j==0,(i,0)的路径数==(i-1,0)的路径数

    2.2 i>0,(i,j)的路径数=(i-1,j)的路径数+(i,j-1)的路径数

    代码:

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
     4         int i,j,m=obstacleGrid.size(),n=obstacleGrid[0].size();
     5         vector<int> cur(n);
     6         cur[0]=1;
     7         for(i=0;i<m;i++){
     8             for(j=0;j<n;j++){
     9                 if(obstacleGrid[i][j]){
    10                     cur[j]=0;
    11                 }
    12                 else{
    13                     if(j>0){
    14                         cur[j]+=cur[j-1];
    15                     }
    16                 }
    17             }
    18         }
    19         return cur[n-1];
    20     }
    21 };
  • 相关阅读:
    Calendar日历类
    DateFormat类和SimpleDateFormat类
    Date时间类(java.util.Date)
    时间处理相关类
    不可变和可变字符序列使用陷阱
    String类
    搬圆桌问题
    重温经典之排序 java实现
    i++ 和 ++i
    Intellij Idea 使用技巧 updating
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5651709.html
Copyright © 2020-2023  润新知