LeetCode 0967. Numbers With Same Consecutive Differences Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0967. Numbers With Same Consecutive Differences

Description

Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order.

Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.

 

Example 1:

Input: n = 3, k = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:

Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

 

Constraints:

  • 2 <= n <= 9
  • 0 <= k <= 9

Solutions

Solution 1: DFS

We can enumerate the first digit of all numbers of length n, and then use the depth-first search method to recursively construct all numbers that meet the conditions.

Specifically, we first define a boundary value boundary = 10n-1, which represents the minimum value of the number we need to construct. Then, we enumerate the first digit from 1 to 9. For each digit i, we recursively construct the number of length n with i as the first digit.

The time complexity is (n × 2n × |Σ|), where |Σ| represents the set of digits, and in this problem |Σ| = 9. The space complexity is O(2n).

PythonJavaC++GoTypeScriptJavaScript
class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def dfs(x: int): if x >= boundary: ans.append(x) return last = x % 10 if last + k <= 9: dfs(x * 10 + last + k) if last - k >= 0 and k != 0: dfs(x * 10 + last - k) ans = [] boundary = 10 ** (n - 1) for i in range(1, 10): dfs(i) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !