967. 连续差相同的数字

返回所有长度为 n 且满足其每两个连续位上的数字之间的差的绝对值为 k 的 非负整数 。
请注意,除了 数字 0 本身之外,答案中的每个数字都 不能 有前导零。例如,01 有一个前导零,所以是无效的;但 0 是有效的。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/numbers-with-same-consecutive-differences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

时常有这种想法,就是为什么在学编程的时候要学“循环”这种东西,超时了。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def numsSameConsecDiff(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
mini_num,max_num = 10**(n-1),10**n
def seperate(num,k):
num = [item for item in str(num)]
flag = True
for i in range(1,len(num)):
if abs(int(num[i]) - int(num[i-1])) != k:
flag = False
if flag:
return int("".join(num))
else:
return None
result = list()
for i in range(mini_num,max_num):
res = seperate(i,k)
if res:
result.append(res)
return result

然后看到了这个题解:

找到了类似思路的代码,但是没看懂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def numsSameConsecDiff(self, N, K):
"""
:type N: int
:type K: int
:rtype: List[int]
"""
if N == 1:
return list(range(10))

res = list(range(1, 10))
for _ in range(1, N):
tmp_res = list()
for num in res:
num_s = num % 10
for i in {num_s - K, num_s + K}:
if 0 <= i <= 9:
tmp_res.append(num * 10 + i)
res = tmp_res
return res