218 - 91 解码方法
题目
一条包含字母 A-Z 的消息通过以下方式进行了编码:
'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: "12" 输出: 2 解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:
输入: "226" 输出: 3 解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
解答
每个数字一个数,两两组合一个数,组合还要看不要超过26
https://leetcode-cn.com/problems/decode-ways/solution/dong-tai-gui-hua-tu-jie-by-nfgc/
class Solution:
def numDecodings(self, s: str) -> int:
pp, p = 1, int(s[0] != "0")
for i in range(1, len(s)):
pp, p = p, pp*(9 < int(s[i-1:i+1]) <= 26)+p*(int(s[i]) > 0)
return pRuntime: 28 ms, faster than 83.56% of Python3 online submissions for Decode Ways.
Memory Usage: 12.5 MB, less than 100.00% of Python3 online submissions for Decode Ways.
https://leetcode.com/problems/decode-ways/discuss/30379/1-liner-O(1)-space
Runtime: 28 ms, faster than 83.56% of Python3 online submissions for Decode Ways.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Decode Ways.
递归
超时了
带备忘录的递归
Runtime: 36 ms, faster than 27.57% of Python3 online submissions for Decode Ways.
Memory Usage: 13.7 MB, less than 16.00% of Python3 online submissions for Decode Ways.
自底向上
https://leetcode.com/problems/decode-ways/discuss/30358/Java-clean-DP-solution-with-explanation
Runtime: 32 ms, faster than 59.69% of Python3 online submissions for Decode Ways.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Decode Ways.
Last updated
Was this helpful?