1
+ """
2
+ 1. Problem Summary / Clarifications / TDD:
3
+ Output(N = 3, K = 7): [181,292,707,818,929]
4
+ Output(N = 3, K = 3): [147,141,258,252,369,363,303,474,414,585,525,696,636,630,747,741,858,852,969,963]
5
+ Output(N = 2, K = 1): [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
6
+
7
+ 2. Intuition:
8
+ 1..9
9
+ / \
10
+ 4 6
11
+ - It's a forest of binary trees of height N - 1:
12
+ - The forest roots value is from 1 to 9
13
+ - Solution2: DFS, BFS
14
+
15
+ 3. Implementation
16
+ 4. Tests:
17
+ Edge Cases:
18
+ Output(N = 1, K = X): [0,1,2,3,4,5,6,7,8,9]
19
+ Output(N = 2, K = 0): [11,22,33,44,55,66,77,88,99]
20
+
21
+ 5. Complexity Analysis:
22
+ - N > 1
23
+ - Each binary tree has a max height of N
24
+ - Each binary tree has at most 2^N-1 paths (from root to leaves): potential candidates
25
+ - Each binary tree has at most 1 + 2 + ... + 2^N-1 = 2^N - 1 nodes
26
+ - The forest has at most 9 * (2^N - 1) nodes and 9 * 2^N-1 paths (results)
27
+ - So our solution could have at most 9 * 2^N-1 numbers
28
+
29
+ """
30
+
31
+ class Solution_DFS :
32
+ """
33
+ Time Complexity:
34
+ - O(1) if N = 1
35
+ - O(N) if K = 0
36
+ - O(9 * (2^N - 1)) = O(2^N)
37
+ Space Complexity:
38
+ - O(1) if N = 1
39
+ - Recursion space + results: O(N) + O(9 * 2^N-1) = O(2^N)
40
+ """
41
+ def nums_same_consec_diff (self , N : int , K : int ) -> List [int ]:
42
+ if N == 1 :
43
+ return [i for i in range (10 )]
44
+
45
+ results = []
46
+ for n in range (1 , 10 ):
47
+ self ._nums_same_consec_diff_dfs (N - 1 , K , results , n )
48
+
49
+ return results
50
+
51
+ def _nums_same_consec_diff_dfs (self , N , K , results , num ):
52
+ if not N :
53
+ results .append (num )
54
+ return
55
+
56
+ tail_digit = num % 10
57
+ num *= 10
58
+ N -= 1
59
+
60
+ if tail_digit + K < 10 :
61
+ self ._nums_same_consec_diff (N , K , results , num + tail_digit + K )
62
+
63
+ if K and tail_digit - K >= 0 :
64
+ self ._nums_same_consec_diff (N , K , results , num + tail_digit - K )
65
+
66
+ class Solution_BFS :
67
+ """
68
+ Time Complexity:
69
+ - O(1) if N = 1
70
+ - O(N) if K = 0
71
+ - O(9 * (2^N - 1)) = O(2^N)
72
+ Space Complexity:
73
+ - O(1) if N = 1
74
+ - results: O(9 * 2^N-1) = O(2^N)
75
+
76
+ """
77
+
78
+ def nums_same_consec_diff (self , N : int , K : int ) -> List [int ]:
79
+ if N == 1 :
80
+ return [i for i in range (10 )]
81
+
82
+ results = []
83
+ for n in range (1 , 10 ):
84
+ results .extend (self ._nums_same_consec_diff_bfs (N - 1 , K , n ))
85
+
86
+ return results
87
+
88
+ def _nums_same_consec_diff_bfs (self , N , K , num ):
89
+
90
+ curr_level = [num ]
91
+ while N :
92
+ next_level = []
93
+ for n in curr_level :
94
+ tail_digit = n % 10
95
+ n *= 10
96
+
97
+ if K and tail_digit - K >= 0 :
98
+ next_level .append (n + tail_digit - K )
99
+
100
+ if tail_digit + K < 10 :
101
+ next_level .append (n + tail_digit + K )
102
+
103
+ curr_level = next_level
104
+ N -= 1
105
+
106
+ return curr_level
0 commit comments