Skip to content

Instantly share code, notes, and snippets.

@acmu
Last active May 19, 2019 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acmu/b098a89325e11be9084276a5c68db7d2 to your computer and use it in GitHub Desktop.
Save acmu/b098a89325e11be9084276a5c68db7d2 to your computer and use it in GitHub Desktop.
leetcode 63题 代码内有链接
/**
* from https://leetcode.com/problems/unique-paths-ii/
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function(obstacleGrid) {
const m = obstacleGrid.length,
n = obstacleGrid[0].length;
const dp = Array(m);
for (let i = 0; i < m; i++) dp[i] = Array(n);
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const prevI = i - 1;
const prevJ = j - 1;
let sum = i === 0 && j === 0 ? 1 : 0;
if (prevI >= 0 && !obstacleGrid[prevI][j]) {
sum += dp[prevI][j];
}
if (prevJ >= 0 && !obstacleGrid[i][prevJ]) {
sum += dp[i][prevJ];
}
dp[i][j] = sum;
if (obstacleGrid[i][j]) {
dp[i][j] = 0;
}
}
}
return dp[m - 1][n - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment