Skip to content

Latest commit

 

History

History
101 lines (81 loc) · 2.25 KB

63.不同路径2.md

File metadata and controls

101 lines (81 loc) · 2.25 KB

63. 不同路径 II

url

题目

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?

输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
输出:2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右

输入:obstacleGrid = [[0,1],[0,0]]
输出:1

方法

code

js

let uniquePathsWithObstacles = obstacleGrid => {
    let m = obstacleGrid.length, n = obstacleGrid[0].length;
    let dp = Array(n + 1).fill(0);
    dp[1] = 1;
    for (let i = 1; i <= m; i ++) {
        for (let j = 1; j <= n; j++) {
            if (obstacleGrid[i - 1][j - 1] === 1) {
                dp[j] = 0;
            } else {
                dp[j] += dp[j - 1];
            }
        }
    }
    return dp[n];
}

go

func uniquePathsWithObstacles(obstacleGrid [][]int) int {
	m, n := len(obstacleGrid), len(obstacleGrid[0])
	dp := make([]int, n + 1)
	dp[1] = 1
	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if obstacleGrid[i-1][j-1] == 1 {
				dp[j] = 0
			} else {
				dp[j] += dp[j - 1]
			}
		}
	}
	return dp[n]
}

java

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