967. Numbers With Same Consecutive Differences

967. Numbers With Same Consecutive Differences

Question

Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.

Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid.

You may return the answer in any order.

Solution

回溯,每次传入上一个数字和剩余的位数。
全局变量sum记录加和。
DFS搜索,每次计算下一位的可行数字并递归。
用回溯维护sum的值。
如果剩余位数为1,则将当前的sum加入结果,并清零sum。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
List<Integer> res;
int sum;
public int[] numsSameConsecDiff(int n, int k) {
res = new ArrayList<>();
for(int i = 1; i < 10; i++){
sum = 0;
dfs(i, n, k);
}

int[] ret = new int[res.size()];
for(int i = 0; i < res.size(); i++){
ret[i] = res.get(i);
}
return ret;
}

private void dfs(int prev, int n, int k){
sum += prev;
if(n == 1){
res.add(sum);
return;
}

if(k == 0){
sum *= 10;
dfs(prev + k, n-1, k);
sum /= 10;
return;
}
if(prev + k < 10){
sum *= 10;
dfs(prev + k, n-1, k);
sum /= 10;
}
if(prev >= k){
sum *= 10;
dfs(prev - k, n-1, k);
sum /= 10;
}
}
}

Author

Xander

Posted on

2022-09-02

Updated on

2022-09-02

Licensed under

Comments