forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumbersWithSameConsecutiveDifferences.java
More file actions
33 lines (29 loc) · 1.01 KB
/
NumbersWithSameConsecutiveDifferences.java
File metadata and controls
33 lines (29 loc) · 1.01 KB
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
class NumbersWithSameConsecutiveDifferences {
public int[] numsSameConsecDiff(int N, int K) {
List<Integer> list = new ArrayList<>();
if(N==1){
list.add(0);
}
dfs(N, K, list, 0);
int[] ans = new int[list.size()];
for(int i=0;i<list.size();i++){
ans[i] = list.get(i);
}
return ans;
}
private void dfs(int N, int K , List<Integer> list, int currNo){
if(N<=0){
list.add(currNo); // loop out of recussion
return ;
}
for(int i=0;i<10;i++){
if(i==0 && currNo ==0){ // skip the case of leading 0
continue;
} else if(i!=0&& currNo ==0){ // base case when currNo is 0
dfs(N-1, K, list, i);
} else if(Math.abs(currNo%10 - i)==K){
dfs(N-1, K, list, currNo*10+ i); // adding i at the units place of the currNO (Valid case where the difference between previous digit and i is K)
}
}
}
}