63. Unique Paths II (M)

本文探讨了在包含障碍物的网格中寻找从左上角到右下角的不同路径数量的问题。介绍了如何应用动态规划解决该问题,包括标准动态规划和滚动数组优化两种方法。

Unique Paths II (M)

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).

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.

Note: m and n will be at most 100.

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

题意

在矩形中找到一条路径,起点为左上顶点,终点为右下顶点,路径中只能向右或向下走,且矩形中存在不能通过的障碍点,要求统计不同路径的个数。

思路

62. Unique Paths 方法一致,只是多了障碍点不好用组合数解决问题。使用动态规划,并用滚动数组进行优化。


代码实现 - 动态规划

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[][] dp = new int[n][m];
        
        dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (i != 0 || j != 0) {
                    dp[i][j] = obstacleGrid[i][j] == 1 ? 0 : 
                    		((i == 0 ? 0 : dp[i - 1][j]) + (j == 0 ? 0 : dp[i][j - 1]));
                }
            }
        }
        
        return dp[n - 1][m - 1];
    }
}

代码实现 - 滚动数组优化

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[] dp = new int[m];
        
        dp[0] = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[j] = obstacleGrid[i][j] == 1 ? 0 : j > 0 ? dp[j - 1] + dp[j] : dp[j];
            }
        }
        
        return dp[m - 1];
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值