91. Decode Ways
2016-04-23 15:24
393 查看
Problem
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.
一道不错的动态规划题目,一开始自己写的不对,后来参考了disscuss。
注意字符串开头为0的情况。
Solution
动态规划。使用dp1表示截至到s[i-1]的解码方式的个数,dp2表示截至s[i-2]的解码方式的个数。
当s[i]为’0’时,不能单独存在,必须与前一个数字结合,所以dp1 = 0;
如果s[i-1]为’1’或s[i-1] == ‘2’而且 s[i] <= ‘6’,那么dp1 = dp1 + dp2,dp2=dp1-dp2,即dp1的旧值。
否则,dp2=dp1;
class Solution { public: int numDecodings(string s) { if(s.empty() || s[0] == '0') return 0; int len = s.length(); //decoding ways to s[i-1] int dp1 = 1; //decoding ways to s[i-2] int dp2 = 1; for(int i = 1;i<len;++i) { // zero voids ways of the last because zero cannot be used separately if(s[i] == '0') dp1 = 0; // possible two-digit letter, so new r1 is sum of both while new r2 is the old r1 if(s[i-1] == '1' || (s[i-1] == '2' && s[i] <= '6')) { dp1 = dp1 + dp2; dp2 = dp1 - dp2; } // one-digit letter, no new way added else dp2 = dp1; } return dp1; } };
相关文章推荐
- iOS 压力测试
- Nginx安装
- "围观"设计模式(8)--创建型之简单工厂模式、工厂方法模式、抽象工厂模式
- ubuntu14.04安装subversion1.8相关问题
- iOS-获取视频长度和当前播放时间
- 聊聊Android编程规范
- "围观"设计模式(7)--创建型之单例模式(Singleton Pattern)
- 编写一个函数实现atoi()函数,即把字符串数字转变为数字
- Flex Builder中创建的项目4种
- UIApplication
- JavaScript中的onchange、oninput以及onpropertychange
- maven repository mirror:
- Android自定义圆形进度条,结合AsyncTask下载显示进度
- "围观"设计模式(6)--开闭原则(Open/Closed Principle)
- 数据库连接池的工作原理
- 搜索—Problem_1016-Red and Black
- OpenCv学习笔记--支持向量机SVM线性可分情况下的OpenCv实现的超详细注释(2)
- Django - 文件上传
- MySQL绿色版安装(mysql-5.7.12-win32)
- Angular源码解析参考文章