我做在Python过程中的一些excercises,其中一人在那里我被困低于:如何应用回溯算法?
Given a digit sequence that represents a message where each uppercase letter
is replaced with a number (A - 1, B - 2, ... , Z - 26) and space - 0.
Find the number of the initial messages, from which that sequence
could be obtained.
Example: 12345 - 3 (ABCDE, LCDE, AWDE)
11 - 2 (AA, K)
天真的解决方案是容易的,它是简单的暴力破解的算法:
import string
def count_init_messages(sequence):
def get_alpha(seq):
nonlocal count
if len(seq) == 0:
count += 1
return
for i in range(1, len(seq) + 1):
if seq[:i] not in alph_table:
break
else:
get_alpha(seq[i:])
alphabet = " " + string.ascii_uppercase
# generate dictionary of possible digit combination
alph_table = {str(n): alph for n, alph in zip(range(len(alphabet)), alphabet)}
# counter for the right combination met
count = 0
get_alpha(sequence)
return count
def main():
sequence = input().rstrip()
print(count_init_messages2(sequence))
if __name__ == "__main__":
main()
但因为输入序列的长度可能长达100个字符,并且可能会有很多重复,所以我遇到了一个时间限制。例如,其中一个示例输入是2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129)
。由于我的实现过多重复,处理这种输入需要很长时间。我想到使用回溯算法,但我还没有意识到如何实现成功的成果。
如果能够指出我如何打破这一任务,我会很高兴。
它似乎破坏了'12345'输入 – Ashot
@Ashot - 谢谢,你说得对。索引被关闭了[[i-1:i]'应该是'[i-1:i + 1]'。现在修复。 –
@PaulHankin,谢谢你的想法,但它不会用于输入'11101'。你的代码给出输出'2',而我的正确答案是'5'。是否应以不同方式积累总和? – vpetrigo