Q :
返回所有长度为 N
且满足其每两个连续位上的数字之间的差的绝对值为 K
的非负整数。
请注意,除了数字 0
本身之外,答案中的每个数字都不能有前导零。例如,01
因为有一个前导零,所以是无效的;但 0
是有效的。
你可以按任何顺序返回答案。
示例 1:
输入:N = 3, K = 7 输出:[181,292,707,818,929] 解释:注意,070 不是一个有效的数字,因为它有前导零。
示例 2:
输入:N = 2, K = 1 输出:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
链接:https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences/
思路:主要就是一个遍历的过程,对于每次一遍历的末位,分别加K或者-K,判断是否大于0,记录下来,思路很傻,效率不好,效率不好的原因主要是由于各种int转str 这个很消耗时间
代码:
class Solution:
def numsSameConsecDiff(self, N, K):
"""
:type N: int
:type K: int
:rtype: List[int]
"""
if N == 0:
return []
if N == 1:
return [i for i in range(10)]
res = [str(i) for i in range(1, 10)]
while N > 1:
r1 = []
r2 = []
for i in range(len(res[:])):
temp1 = int(res[i][-1]) - K
temp2 = int(res[i][-1]) + K
if temp1 < 10 and temp1 >= 0:
r1.append(res[i] + str(temp1))
if temp2 < 10 and temp2 >= 0:
r2.append(res[i] + str(temp2))
res = []
res += r1
res += r2
N -= 1
res_ = [int(r) for r in res]
return list(set(res_))