91. Decode Ways
2017-02-26 23:03
113 查看
问题描述
A message containing letters from A-Z is being encoded to numbers using the following mapping:
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.
解决思路
很简单的动态规划的解法,但是需要注意’0’的情况,不同情况状态转移函数不同。
代码
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.
解决思路
很简单的动态规划的解法,但是需要注意’0’的情况,不同情况状态转移函数不同。
代码
class Solution { public: int numDecodings(string s) { if (s.length() == 0) return 0; if (s.length() == 1 && s[0] >'0' && s[0] <= '9') return 1; else if(s.length() == 1) return 0; if (s[0] == '0') return 0; int len = s.length(); vector<int> dp(len,0); if (dp[0] == '0') dp[0] = 0; else dp[0] = 1; int num = (s[0]-'0') * 10 + (s[1]-'0'); if (num <= 26 && num % 10 != 0 && num > 9) dp[1] = 2; else if ((num > 26 && num%10 != 0) || num == 10 || num == 20) dp[1] = 1; else if (num > 0) return 0; for (int i = 2; i < len; ++i) { if (s[i] == '0' && s[i-1] < '3' && s[i-1] > '0') { dp[i] = dp[i-1] = dp[i-2]; } else if (s[i] == '0') return 0; else { num = (s[i-1]-'0') * 10 + (s[i]-'0'); if (num > 9 && num <= 26) dp[i] = dp[i-1]+dp[i-2]; else dp[i] = dp[i-1]; } } return dp[len-1]; } };
相关文章推荐
- [LeetCode] 91. Decode Ways
- 91. Decode Ways
- Leetcode-91. Decode Ways
- 91. Decode Ways 动态规划-极客学院
- leetcode 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- leetcode - 198,213. House Robber(II) & 91. Decode Ways
- 91. Decode Ways
- [leetcode] 91. Decode Ways
- 【LeetCode】91. Decode Ways
- 91. Decode Ways
- leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- 【DP】递推【91. Decode Ways】
- LeetCode 91. Decode Ways
- leetcode 91. Decode Ways
- leecode 解题总结:91. Decode Ways
- 91. Decode Ways
- leetcodeOJ 91. Decode Ways