91. Decode Ways
Problem description:
A message containing letters from A-Z is being encoded to numbers using the following mapping:1
2
3
4'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:1
2Input: "12"
Output: 2
Explanation: It could be decoded as “AB” (1 2) or “L” (12).
Example 2:1
2Input: "226"
Output: 3
Explanation: It could be decoded as “BZ” (2 26), “VF” (22 6), or “BBF” (2 2 6).
Solution:
example:1
2
3
4
5
6
7
8
9
10
111. basic case:
"3"-> c, num_ways("3")= 1
""-> "", num_ways("")= 1
2. common cases:
"12345", num_ways("2345")+num_ways("345")
"27345", nums_ways("7345")
3. exception:
"011", num_ways("011")= 0
Use a dp array of size n + 1 to store the subproblem solutions.
dp[0] means an empty string will have one way to decode.
dp[1] means the way to decode a string of size 1.
For other cases, check one digit(dp[i-1]
) and two digit(dp[i-2]
) combination and save the results along the way. In the end, dp[n] will be the end result.
1 | class Solution: |
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(n)$