Skip to content

Commit 11f1079

Browse files
967. Numbers With Same Consecutive Differences
Difficulty: Medium 92 / 92 test cases passed. Runtime: 28 ms Memory Usage: 14.2 MB
1 parent 86928ed commit 11f1079

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Return all non-negative integers of length N such that the absolute
3+
difference between every two consecutive digits is K.
4+
Note that every number in the answer must not have leading zeros except for
5+
the number 0 itself. For example, 01 has one leading zero and is invalid,
6+
but 0 is valid.
7+
You may return the answer in any order.
8+
9+
Example:
10+
Input: N = 3, K = 7
11+
Output: [181,292,707,818,929]
12+
Explanation: Note that 070 is not a valid number, because it has leading
13+
zeroes.
14+
15+
Example:
16+
Input: N = 2, K = 1
17+
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
18+
19+
Note:
20+
1. 1 <= N <= 9
21+
2. 0 <= K <= 9
22+
"""
23+
#Difficulty: Medium
24+
#92 / 92 test cases passed.
25+
#Runtime: 28 ms
26+
#Memory Usage: 14.2 MB
27+
28+
#Runtime: 28 ms, faster than 99.53% of Python3 online submissions for Numbers With Same Consecutive Differences.
29+
#Memory Usage: 14.2 MB, less than 21.86% of Python3 online submissions for Numbers With Same Consecutive Differences.
30+
31+
class Solution:
32+
33+
def numsSameConsecDiff(self, N: int, K: int) -> List[int]:
34+
self.K = K
35+
self.nums = []
36+
if N == 1:
37+
return [n for n in range(10)]
38+
for num in range(1, 10):
39+
self.dfs(N-1, num)
40+
return self.nums
41+
42+
def dfs(self, N, num):
43+
if N == 0:
44+
self.nums.append(num)
45+
return
46+
digit = num % 10
47+
if digit >= self.K:
48+
self.dfs(N-1, num*10+digit-self.K)
49+
if self.K > 0 and digit + self.K < 10:
50+
self.dfs(N-1, num*10+digit+self.K)

0 commit comments

Comments
 (0)