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

LeetCode 78 - Subsets (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 78๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋ฉฑ ์ง‘ํ•ฉ ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•์ด ์žˆ๊ฒ ์ง€๋งŒ ์ €๋Š” ๋น„ํŠธ ๋งˆ์Šคํฌ ๋ฅผ ํ†ตํ•ด์„œ ๋ชจ๋“  ๋ถ€๋ถ„ ์ง‘ํ•ฉ์„ ์ƒ์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค.

ํ•œ๊ฐ€์ง€ ์œ ์˜ํ•  ์ ์€ ๋ฐ˜๋ณต๋ฌธ์„ ์ง์ ‘ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  filter ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด
subset ์— ํฌํ•จ๋œ ๋ชจ๋“  ๋น„ํŠธ๋ฅผ ์ฐพ์•„์„œ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function (nums) {
  let numbers = 0;

  nums.forEach((n) => {
    numbers |= 1 << n;
  });

  const answer = [[]];
  for (let subset = numbers; subset; subset = (subset - 1) & numbers) {
    const temp = nums.filter((n) => subset & (1 << n));
    answer.push(temp);
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€