๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 62 - Unique Paths (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 62๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ „ํ˜•์ ์ธ ๋™์  ๊ณ„ํš๋ฒ• ์„ ํ™œ์šฉํ•œ ๊ฒฝ๋กœ ์ฐพ๊ธฐ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์‹œ์ž‘ ์ง€์ ์—์„œ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉํ–ฅ์ด ์˜ค๋ฅธ์ชฝ๊ณผ ์•„๋ž˜์ชฝ์œผ๋กœ ๊ณ ์ •๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์—
dp(x, y) = (x, y) ์ง€์ ์—์„œ finish์— ๋„๋‹ฌํ•˜๋Š” ๊ฒฝ๋กœ์˜ ๊ฐœ์ˆ˜ ๋ผ๊ณ  ์ •์˜ํ•œ๋‹ค๋ฉด
๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ ํ™”์‹์„ ์„ธ์šธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

dp(x, y) = dp(x+1, y) + dp(x, y+1)


์ด๋•Œ ๊ฒฉ์ž๋ฅผ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜ finish ์ง€์ ์— ๋„์ฐฉํ•˜๋Š” ๊ธฐ์ € ์‚ฌ๋ก€๋ฅผ ์ฒ˜๋ฆฌํ•ด์ค€๋‹ค๋ฉด ์‰ฝ๊ฒŒ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var uniquePaths = function (m, n) {
  const memo = new Array(m).fill(null).map((_) => new Array(n).fill(-1));

  function dp(x, y) {
    if (x === m - 1 && y === n - 1) {
      return 1;
    } else if (x < 0 || x >= m || y < 0 || y >= n) {
      return 0;
    }

    if (memo[x][y] !== -1) {
      return memo[x][y];
    }

    memo[x][y] = dp(x + 1, y) + dp(x, y + 1);
    return memo[x][y];
  }

  return (ret = dp(0, 0));
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 198 - House Robber (Easy)  (0) 2021.03.02
LeetCode 22 - Generate Parentheses (Medium)  (0) 2021.03.02
LeetCode 121 - Best Time to Buy and Sell Stock (Easy)  (0) 2021.03.02
LeetCode 101 - Symmetric Tree (Easy)  (0) 2021.03.02
LeetCode 876 - Middle of the Linked List (Easy)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€