Numbers With Same Consecutive Differences LeetCode solution in Java

1
class Solution {
2

3
List<Integer> res = new ArrayList<>();
4

5
public int[] numsSameConsecDiff(int n, int k) {
6

7
for (int ans = 1; ans < 10; ans++) { // first digit can't be 0
8
find(ans, n - 1, k); // find remaining n-1 digits using backtrack
9
}
10

11
return res.stream().mapToInt(Integer::intValue).toArray(); // convert list to int arr
12
}
13

14
private void find(int ans, int n, int k) {
15

16
if (n == 0) {
17
res.add(ans); // if got length n number then put that into res
18
return;
19
}
20

21
for (int i = 0; i < 10; i++) {
22
if (Math.abs(ans % 10 - i) == k) // find digit that have k difference with last digit
23
find(ans * 10 + i, n - 1, k);
24
}
25
ans /= 10; // remove last digit while backtrack
26
}
27
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0