๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ/LeetCode

[LeetCode] Numbers With Same Consecutive Differences

๋ฌธ์ œ๋งํฌ

 

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