1. 解题思路
这一题我的思路的话就是首先计算出所有 1 0 17 10^{17} 1017以下的所有满足条件的特殊回文数字,然后根据具体的 n n n进行查找即可。
而要涉及如何获取所有 1 0 17 10^{17} 1017以下的特殊回文数字,我们就是使用一个迭代的算法即可,我们只要考察每一个数字的使用情况,然后考察单侧的可能排序方法,然后将其返回即可。
2. 代码实现
给出python代码实现如下:
def get_special_palindrome():
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
ans = set()
def get_candidates(idx, candidates):
nonlocal ans
if len(candidates) > 8:
return
if idx < 4:
get_candidates(idx+1, candidates)
get_candidates(idx+1, candidates + [even[idx]] * (even[idx]//2))
else:
if len(candidates) > 0:
for purb in permutations(candidates):
sub = "".join([str(x) for x in purb])
ans.add(int(sub + sub[::-1]))
for num in odd:
dup = [str(num)] * (num//2)
candi = candidates + dup
if len(candi) > 8:
break
for purb in permutations(candi):
sub = "".join([str(x) for x in purb])
ans.add(int(sub + str(num) + sub[::-1]))
return
get_candidates(0, [])
return sorted(ans)
SPECIAL_PALINDROME = get_special_palindrome()
class Solution:
def specialPalindrome(self, n: int) -> int:
idx = bisect.bisect_right(SPECIAL_PALINDROME, n)
return SPECIAL_PALINDROME[idx]
提交代码评测得到:耗时0ms,占用内存18.36MB。
2117

被折叠的 条评论
为什么被折叠?



