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

LeetCode 89 - Gray Code (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 89๋ฒˆ

ํ’€์ด ๊ณผ์ •

n ์ž๋ฆฌ์˜ gray code ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

gray code ๋Š” ์ธ์ ‘ํ•œ ๋น„ํŠธ 1๊ฐœ๋ฅผ ๋ฐ”๊พธ๋Š” ๋ฐฉ์‹์œผ๋กœ ๋งŒ๋“ค์–ด๊ฐ‘๋‹ˆ๋‹ค.
4์ž๋ฆฌ์˜ gray code ๋ฅผ ๋ณด๋ฉด ํŠน์ •ํ•œ ๊ทœ์น™์„ฑ์ด ์กด์žฌํ•˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ์žฌ๊ท€ ํ˜ธ์ถœ ๋กœ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  gray code ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  10 ์ง„์ˆ˜๋กค ๋ณ€ํ™˜ํ•ด์„œ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number} n
 * @return {number[]}
 */
var grayCode = function (n) {
  if (n === 0) return [0];

  function code(bit) {
    if (bit > n) return [""];

    const subsets = code(bit + 1);
    const zeroStart = subsets.map((sub) => "0" + sub);
    const oneStart = subsets.reverse().map((sub) => "1" + sub);

    return zeroStart.concat(oneStart);
  }

  const answer = code(1).map((code) => parseInt(code, 2));
  return answer;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€