91. Decode Ways
Leetcode
https://leetcode.com/problems/decode-ways/description/
題目
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF"with the grouping(1 1 10 6)"KJF"with the grouping(11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The test cases are generated so that the answer fits in a 32-bit integer.
解答
方法一 - 遞歸
範例:s = '2261'
從前兩個字母切分來看會有兩種方式:
單獨切分第一個字母:
2|216可能的組合為 (2, 2, 1, 6), (2, 2, 16), (2, 21, 6)
切分前兩個字母:
22|16可能的組合為 (22, 1, 6), (22, 16)
所以要求出 2261 總共會有幾種解碼,就是 2|216 + 22|16 兩種組合加起來的數目,也就是五種
結果:TLE
方法二 - 遞歸 + memorization
為了避免上一個方法有許多重複的計算,所以多增加使用 memo 的方式讓測資可以通過
方法三 - DP
DP[i] 代表從第 i 個元素開始到最後一個元素為止,總共可能的解碼方式
所以按照方法一統整出來的邏輯 => DP[i] = DP[i+1] + DP[i+2]
問題
為什麼
dp[s.length]初始化為1?
假設 s = '213'
dp[2]等於1dp[1] = dp[2] + dp[3] = 1 + dp[3]dp[1]全部的組合有 (1, 3), (13),總共兩種,所以為了要讓dp[1] = dp[2] + dp[3]的算式成立,會把 最後一個元素後面的 DP (dp[s.length]) 初始化為1
參考資料
Last updated