我做在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