慕桂英4014372
您可以通过注意每次将数字添加到现有的步进数字时,它必须比现有的最后一位数字多 1 或少 1,从而简化数字的生成。因此,我们可以生成具有给定位数的所有步进数字,方法是从单个数字 (1-9) 开始,然后向它们重复添加数字,直到达到我们想要的位数。因此,例如,从 digit 开始1,需要转到 4 位数字,我们将产生1 => 10, 1210, 12 => 101, 121, 123101, 121, 123 => 1010, 1012, 1210, 1212, 1232, 1234我们需要的位数是使用 计算的math.ceil(math.log10(N))。import mathdef stepNums(N): if N < 10: return -1 digits = math.ceil(math.log10(N)) sn = [[]] * digits # 1 digit stepping numbers sn[0] = list(range(1, 10)) # m digit stepping numbers for m in range(1, digits): sn[m] = [] for s in sn[m-1]: if s % 10 != 0: sn[m].append(s * 10 + s % 10 - 1) if s % 10 != 9: sn[m].append(s * 10 + s % 10 + 1) return [s for l in sn for s in l if 10 <= s <= N]例如print(stepNums(3454))输出:[10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98, 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, 345, 432, 434, 454, 456, 543, 545, 565, 567, 654, 656, 676, 678, 765, 767, 787, 789, 876, 878, 898, 987, 989, 1010, 1012, 1210, 1212, 1232, 1234, 2101, 2121, 2123, 2321, 2323, 2343, 2345, 3210, 3212, 3232, 3234, 3432, 3434, 3454]请注意,通过将生成的数字与 进行比较,可以加快代码的运行速度,N这样在调用时stepNums(10001)我们就不会生成直到98989.
牛魔王的故事
也许这里的主要技巧是最大范围是 10^7。如果我们把每个数字看成图的一个节点,我们可以用bfs/dfs遍历它,在每个点上,我们只能移动到相邻的节点(数字+1,数字-1)。因为最大深度只有 7,所以解决方案应该很快。这是一个粗略的DFS实现,你可以改进细节。sol_list = []def dfs(i, num, N): # print(i, num) if num > N: # too much, need to break return if num <= N and num >= 10: # perfect range, add to solution, I can add some repeated solution as I called dfs(i+1,0,N) multiple times global sol_list # print(num) sol_list.append(num) # add to solution if i > 7: return if num == 0: # I can call another 0 dfs(i+1, 0, N) # this is not needed if the numbers are added in the previous list without checking last_dig = num % 10 if last_dig == 0: dfs(i+1, num*10 + 1, N) # if last digit is 0, we can only choose 1 as next digit not -1 elif last_dig == 9: dfs(i+1, num*10 + 8, N) else: dfs(i+1, num*10 + (last_dig-1), N) dfs(i+1, num*10 + (last_dig+1), N)import timet1 = time.time()[dfs(0, i, 10000000) for i in range(10)] # staring with every digit possible 0-9t2 = time.time()print(t2-t1)sol = sorted(set(sol_list))print(sol) # added some repeated solutions, it's easier to set them