LeetCode简易题解--091
2017-12-05 19:42
225 查看
题目描述:有以下映射表:
给定一个字符串,根据映射表判断有多少种组合方式。
比如:
Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).
这道题可以用动态规划求解,基本思路是比较简单的。
那么,状态转移方程为:
这两个状态转移方程并不难想,但是当实际开始做的时候,很容易忽略0产生的特殊情况。并且测试样例中还可能出现
比较简单,最后直接看代码:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
给定一个字符串,根据映射表判断有多少种组合方式。
比如:
Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).
这道题可以用动态规划求解,基本思路是比较简单的。
dp[i]表示
s[0...i]有多少种组合方式。
那么,状态转移方程为:
dp[i] = dp[i - 1] + dp[i - 2]; 如果int(s[i-1]s[i]) >= 10 或者 <= 26
dp[i] = dp[i - 1]; 如果int(s[i-1]s[i])不是合法数字
这两个状态转移方程并不难想,但是当实际开始做的时候,很容易忽略0产生的特殊情况。并且测试样例中还可能出现
00这样的字串。在做的过程中可能没法把一些特殊情况考虑完善。
比较简单,最后直接看代码:
class Solution { public: int numDecodings(string s) { int n = s.size(); if (n == 0 || s[0] == 48) return 0; vector<int> dp(n, 0); // 由于状态转移方程涉及到dp[i-2],需要先对dp[0],dp[1]进行处理 dp[0] = 1; if (s[1] == 48 && !(s[0] == 49 || s[0] == 50)) // 非法数字 return 0; if (s[1] == 48) dp[1] = dp[0]; else dp[1] = 1 + (s[0] == 49 || (s[0] == 50 && s[1] <= 54)); for (int i = 2; i < n; ++i) { if (s[i] == 48 && !(s[ 4000 i - 1] == 49 || s[i - 1] == 50)) // 非法数字 return 0; if (s[i] != 48) dp[i] += dp[i - 1]; if (s[i - 1] == 49 || (s[i - 1] == 50 && s[i] <= 54)) dp[i] += dp[i - 2]; } return dp[n - 1]; } };
相关文章推荐
- LeetCode简易题解--084,085
- LeetCode简易题解--098、099
- [LeetCode]题解(python):091-Decode Ways
- LeetCode简易题解--120
- LeetCode简易题解--375
- LeetCode简易题解--105、106
- LeetCode简易题解--103
- LeetCode简易题解--221
- LeetCode简易题解--053
- LeetCode简易题解--121、122、123、188
- LeetCode简易题解--039
- LeetCode简易题解--629
- Decode Ways|leetcode题解
- LeetCode题解:First Bad Version
- leetcode题解-105 && 106. Construct Binary Tree from Preorder (PostOrder) and Inorder Traversal
- leetcode题解-71. Simplify Path
- 【特别重要!!!快排的partition思想】【leetcode题解】【M】【71】Kth Largest Element in an Array
- leetcode题解-459. Repeated Substring Pattern && 443. String Compression && 434. Number of Segments in
- 【leetcode题解】【E】【59】Reverse Bits
- LeetCode(11)题解: Container With Most Water