μ½λ©ν
μ€νΈ/LeetCode
[LeetCode] Numbers With Same Consecutive Differences
μ€μ½λ©
2022. 9. 3. 17:20
λ¬Έμ λ§ν¬
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;
};