91. Decode Ways
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了91. Decode Ways相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/decode-ways/#/description
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
‘A‘ -> 1 ‘B‘ -> 2 ... ‘Z‘ -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
Sol:
This is a dynamic programming problem.
We will examine two digits at one time. Encodeable cases like 01, 23, 20. Unencodeable cases like 09, 01.
First we will figure out under what circumstances that two ways of decoding are generated. If the messages are like, 11, 12, 13, ... , 26 then we have two ways to decode messages.
dp[i] = dp[i-1] + dp[i-2]
Then we find out when the message can only be interpreted into one way. Following instances above, they are 10, 20, 31, 72, ... One common feature among 31, 72..., -- apart from 10 and 20 -- is that the second digit is not 0.
For 10 and 20:
dp[i] = dp[i-2]
For 21, 31, etc.:
dp[i] = dp[i-1]
Next, lots of numbers can not be decoded anyway. For example, 01, 09. To be more specific on 01, 1) 0, 1 can not be encoded seperately because 0 does not represent any letter. 2) 01 can not be encoded as one letter either.
Before we gonna program this out, initialize dp with [1,1]
i.e. dp[0] = 1, dp[1] = 1
class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ if len(s) == 0 or int(s[0]) == 0: return 0 dp = [1,1] for i in range(2, len(s)+1): if 10 <= int(s[i-2:i]) <= 26 and int(s[i-1]) != 0: dp.append(dp[i-1] + dp[i-2]) elif int(s[i-2:i]) == 10 or int(s[i-2:i]) == 20: dp.append(dp[i-2]) elif int(s[i-1]) != 0: dp.append(dp[i-1]) else: return 0 return dp[len(s)]
Note:
1 For strings, use append rather then + to achieve the mathmatical plus function.
2 int() transforms stuff within parenthesis into integers.
0 without quotes is an integer.
"0" with quotes is a string.
Never check if a string equals to an integer. Transform them into the same data type before comparation.
3 Use the following codes to traverse all two digit chars in string s.
for i in range(2, len(s) + 1):
s[i - 2:i] ......
Need initialize some variables when i = 0 and 1
以上是关于91. Decode Ways的主要内容,如果未能解决你的问题,请参考以下文章