λ¬Έμ
νμ΄ κ³Όμ
μμ μ§μ μμ λͺ©ν μ§μ μ λλ¬ν μ μλ κ²½μ°μ μλ₯Ό μ°Ύλ λ¬Έμ μ
λλ€.dp(x, y)
λ₯Ό (x, y)
μμ μ€λ₯Έμͺ½ νλ¨ λͺ¨μ리μ λλ¬νλ κ²½μ°μ μλΌκ³ νλ€λ©΄ λ€μκ³Ό κ°μ μ νμμ μ μν μ μμ΅λλ€.
dp(x, y) = dp(x + 1, y) + dp(x, y + 1)
μ΄λ dp(x, y)
μλ μ₯μ λ¬Όμ΄ μμ΄μΌ νλ©° 격μλ₯Ό λ²μ΄λλ©΄ μλ©λλ€.
μ½λ
/**
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function (obstacleGrid) {
const m = obstacleGrid.length;
const n = obstacleGrid[0].length;
const memo = Array.from(Array(m), () => Array(n).fill(-1));
function checkValidation(position) {
if (
position[0] < 0 ||
position[0] >= m ||
position[1] < 0 ||
position[1] >= n
)
return false;
return obstacleGrid[position[0]][position[1]] === 0;
}
function getPath(x, y) {
if (x == m - 1 && y == n - 1) {
return 1;
}
if (memo[x][y] !== -1) return memo[x][y];
memo[x][y] = 0;
const candidates = [
[x, y + 1],
[x + 1, y],
];
for (const position of candidates) {
if (checkValidation(position)) {
memo[x][y] += getPath(position[0], position[1]);
}
}
return memo[x][y];
}
if (obstacleGrid[0][0] === 1 || obstacleGrid[m - 1][n - 1] === 1) return 0;
const answer = getPath(0, 0);
return answer;
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 904 - Fruit Into Baskets (Medium) (0) | 2021.03.08 |
---|---|
LeetCode 112 - Path Sum (Easy) (0) | 2021.03.04 |
LeetCode 1011 - Capacity To Ship Packages Within D Days (Medium) (0) | 2021.03.04 |
LeetCode 881 - Boats to Save People (Medium) (0) | 2021.03.04 |
LeetCode 234 - Palindrome Linked List (Easy) (0) | 2021.03.04 |
π¬ λκΈ