Skip to content

Commit 48819af

Browse files
committed
feat: finish no.967
1 parent 1f2788d commit 48819af

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# 967. Numbers With Same Consecutive Differences
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Backtracking, Breadth-First Search.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
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**.
10+
11+
Note that the integers should not have leading zeros. Integers as ```02``` and ```043``` are not allowed.
12+
13+
 
14+
Example 1:
15+
16+
```
17+
Input: n = 3, k = 7
18+
Output: [181,292,707,818,929]
19+
Explanation: Note that 070 is not a valid number, because it has leading zeroes.
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: n = 2, k = 1
26+
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
27+
```
28+
29+
 
30+
**Constraints:**
31+
32+
33+
34+
- ```2 <= n <= 9```
35+
36+
- ```0 <= k <= 9```
37+
38+
39+
40+
## Solution
41+
42+
```javascript
43+
/**
44+
* @param {number} n
45+
* @param {number} k
46+
* @return {number[]}
47+
*/
48+
var numsSameConsecDiff = function(n, k) {
49+
var res = [];
50+
for (var i = 1; i < 10; i++) {
51+
helper([i], n - 1, k, res);
52+
}
53+
return res;
54+
};
55+
56+
var helper = function(arr, n, k, res) {
57+
if (n === 0) {
58+
res.push(+arr.join(''));
59+
return;
60+
}
61+
if (n < 0 || n > 9) {
62+
return;
63+
}
64+
var last = arr[arr.length - 1];
65+
if (last - k >= 0) {
66+
arr.push(last - k);
67+
helper(arr, n - 1, k, res);
68+
arr.pop();
69+
}
70+
if (k !== 0 && last + k < 10) {
71+
arr.push(last + k);
72+
helper(arr, n - 1, k, res);
73+
arr.pop();
74+
}
75+
};
76+
```
77+
78+
**Explain:**
79+
80+
Start with 1 ~ 9, dfs (top down) to get all answers.
81+
82+
**Complexity:**
83+
84+
* Time complexity : O(n).
85+
* Space complexity : O(n).

0 commit comments

Comments
 (0)