私はPythonの過程でいくつかのエクササイズをやっていると私はこだわっているそのうちの一つは以下の通りです:バックトラッキングアルゴリズムの適用方法は?
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文字までになる可能性があり、時間制限を満たしていることが多かったかもしれません。たとえば、サンプル入力の1つは2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129)
です。私の実装はあまりにも多くの繰り返しを行うので、そのような入力を処理するには時間がかかります。私はバックトラッキングアルゴリズムを使うことを考えていますが、私はまだ成功した結果のためにメモを実装する方法をまだ認識していません。
私は、正しい方法でそのタスクを中断する方法を教えてもらえれば嬉しいです。
'12345'入力のために壊れているようです – Ashot
@Ashot - ありがとう、あなたは正しいです。索引付けがオフであった '[i-1:i]'は '[i-1:i + 1]'であったはずです。今修正されました。 –
@PaulHankin、ありがとうございますが、入力 '11101'ではうまくいかないでしょう。あなたのコードは、出力が「2」であり、正解が「5」です。合計は何とか別の方法で蓄積されるべきですか? – vpetrigo