๋ฌธ์ ๋งํฌ
Numbers With Same Consecutive Differences - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
ํ์ฌ ์๋ฆฌ์์ ์ด์ ์๋ฆฌ์, ์ดํ ์๋ฆฌ์๋ฅผ ๋บ ์ ๋๊ฐ์ด k๋ฅผ ๋ง์กฑํ๋ ๋ชจ๋ ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
n์ ๋ฐํ ์ซ์์ ์๋ฆฌ์, k๋ ๋ฐํ ์ซ์์ ์ธ์ ํ ์๋ฆฌ์๋ผ๋ฆฌ์ ์ฐจ์ ์ ๋๊ฐ์ ์๋ฏธํ๋ค.
์กฐ๊ฑด : 0์ผ๋ก ์์ํ๋ ์๋ ์ฌ ์ ์๋ค.
2 <= n <= 9, 0 <= k <= 9
์ ๊ทผ ๋ฐฉ๋ฒ
n = 3, k = 4์ผ๋ ํ๋์ ์๋ฅผ ๋ค์ด๋ณด๋ฉด
1 5 1 9
์ด์ฒ๋ผ 1 => 15 => 151 or 159 ๋ผ๋ ๋ฐฉ์์ผ๋ก ์งํํ ์ ์๋ค. (DFS ๋ฌธ์ )
์ฆ, ํ์ฌ์ ๊ฐ์ k๋ฅผ ๋ํ๊ฑฐ๋ ๋บ ๊ฐ์ด 0 ~ 9 ์ฌ์ด๋ฉด ์ถ๊ฐํ๋ ๋ฐฉ์์ผ๋ก ์งํํ ์ ์๋ค.
/**
* @param {number} n
* @param {number} k
* @return {number[]}
*/
var numsSameConsecDiff = function (n, k) {
const output = [];
const DFS = (n, num) => {
if (n === 0) return output.push(num);
const lastDigit = num % 10;
const nextDigits = new Set([lastDigit - k, lastDigit + k]);
for (const nextDigit of nextDigits) {
if (0 <= nextDigit && nextDigit < 10) {
const newNum = num * 10 + nextDigit;
DFS(n - 1, newNum);
}
}
};
for (let num = 1; num < 10; num++) {
DFS(n - 1, num);
}
return output;
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Rotate Image (0) | 2022.08.30 |
---|---|
[LeetCode] Reduce Array Size to The Half (0) | 2022.08.18 |
[LeetCode] Unique Morse Code Words (0) | 2022.08.17 |
[LeetCode] Combination Sum IV (0) | 2022.08.05 |
[LeetCode] My Calendar I (0) | 2022.08.03 |