๋ฌธ์
ํ์ด ๊ณผ์
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;
};
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 187 - Repeated DNA Sequences (Medium) (0) | 2021.03.03 |
---|---|
LeetCode 3 - Longest Substring Without Repeating Characters (Medium) (0) | 2021.03.03 |
LeetCode 118 - Pascal's Triangle (Easy) (0) | 2021.03.03 |
LeetCode 19 - Remove Nth Node From End of List (Medium) (0) | 2021.03.03 |
LeetCode 79 - Word Search (Medium) (0) | 2021.03.03 |
๐ฌ ๋๊ธ