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

LeetCode 416 - Partition Equal Subset Sum (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 416๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ๋‘ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‘ ๊ทธ๋ฃน์˜ ํ•ฉ์ด ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

0-1 knapsack ๋ฌธ์ œ์™€ ๋น„์Šทํ•˜๊ฒŒ ํŠน์ • ์ธ๋ฑ์Šค์˜ ์ˆซ์ž๋ฅผ ์„ ํƒํ• ์ง€ ์•ˆํ• ์ง€๋ฅผ ๋”ฐ์ ธ์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
์šฐ์„  ๋ชฉํ‘œ ํ•ฉ target = total / 2 ์ด๋ฉฐ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋Š” ํ•ด๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ ์ด๋ฅผ ๋”ฐ๋กœ ์˜ˆ์™ธ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
๊ทธ ๋‹ค์Œ dp[i, k] = i ์ดํ›„ ์ˆซ์ž๋“ค์„ ์„ ํƒํ•ด์„œ ํ•ฉ์ด k ๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ๋ผ๊ณ  ์ •์˜ํ•œ๋‹ค๋ฉด
๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ ํ™”์‹์„ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

dp[i, k] = dp[i+1, k-num[i]] or dp[i+1, k]


์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canPartition = function (nums) {
  const acc = nums.reduce((acc, n) => acc + n);
  if (acc % 2) return false;

  const target = acc / 2;
  const memo = new Array(nums.length + 1)
    .fill(0)
    .map((_) => new Array(target + 1).fill(-1));

  function dp(i, k) {
    if (k === 0) return 1;
    else if (i + 1 >= nums.length || k < 0) return 0;

    if (memo[i + 1][k] !== -1) return memo[i + 1][k];

    memo[i + 1][k] = dp(i + 1, k - nums[i]) || dp(i + 1, k);
    return memo[i + 1][k];
  }

  nums.unshift(0);
  const answer = dp(-1, target);
  return answer;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€