[英]Python: How to find all ways to decode a string?
我正在嘗試解決這個問題,但輸入“226”失敗。
問題:使用以下映射將包含來自 AZ 的字母的消息編碼為數字:
'A' -> 1
'B' -> 2
...
'Z' -> 26
給定一個只包含數字的非空字符串,確定解碼它的方法總數。
我的代碼:
class Solution:
def numDecodings(self, s: str) -> int:
decode =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
ways = []
for d in decode:
for i in s:
if str(d) == s or str(d) in s:
ways.append(d)
if int(i) in decode:
ways.append(str(i))
return len(ways)
我的代碼返回 2。它只處理組合 (22,6) 和 (2,26)。
它應該返回 3,所以我不確定如何處理 (2,2,6) 組合。
看起來這個問題可以分解成許多子問題,因此可以遞歸解決
if s[n-1] > "0":
count = number_of_decodings(s,n-1)
if (s[n - 2] == '1' or (s[n - 2] == '2' and s[n - 1] < '7') ) :
count += number_of_decodings(s, n - 2)
if n == 0 or n == 1 :
return 1
編輯:在互聯網上快速搜索,我發現了另一種(更有趣的)方法來解決這個特殊問題,它使用動態規划來解決這個問題
# A Dynamic Programming based function
# to count decodings
def countDecodingDP(digits, n):
count = [0] * (n + 1); # A table to store
# results of subproblems
count[0] = 1;
count[1] = 1;
for i in range(2, n + 1):
count[i] = 0;
# If the last digit is not 0, then last
# digit must add to the number of words
if (digits[i - 1] > '0'):
count[i] = count[i - 1];
# If second last digit is smaller than 2
# and last digit is smaller than 7, then
# last two digits form a valid character
if (digits[i - 2] == '1' or
(digits[i - 2] == '2' and
digits[i - 1] < '7') ):
count[i] += count[i - 2];
return count[n];
上述解決方案解決了復雜度為O(n)的問題,並使用了與斐波那契數問題類似的方法
來源: https : //www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/
這對於遞歸來說似乎很自然。 由於我很無聊,而且第一個答案沒有使用遞歸,也沒有返回實際的解碼,我認為還有改進的空間。 物有所值...
def encodings(str, prefix = ''):
encs = []
if len(str) > 0:
es = encodings(str[1:], (prefix + ',' if prefix else '') + str[0])
encs.extend(es)
if len(str) > 1 and int(str[0:2]) <= 26:
es = encodings(str[2:], (prefix + ',' if prefix else '') + str[0:2])
encs.extend(es)
return encs if len(str) else [prefix]
這將返回可能的解碼列表。 要獲得計數,您只需獲取列表的長度。 這是一個示例運行:
encs = encodings("123")
print("{} {}".format(len(encs), encs))
結果:
3 ['1,2,3', '1,23', '12,3']
另一個示例運行:
encs = encodings("123123")
print("{} {}".format(len(encs), encs))
結果:
9 ['1,2,3,1,2,3', '1,2,3,1,23', '1,2,3,12,3', '1,23,1,2,3', '1,23,1,23', '1,23,12,3', '12,3,1,2,3', '12,3,1,23', '12,3,12,3']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.