91. Decode Ways
来源:互联网 发布:积分入学社保怎么算法 编辑:程序博客网 时间:2024/04/30 22:24
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; }};
0 0
- Leetcode 91. Decode Ways&&639.Decode ways
- [Leetcode] 91. Decode Ways
- LeetCode --- 91. Decode Ways
- [LeetCode]91.Decode Ways
- [leetcode] 91.Decode Ways
- 91. Decode Ways
- Algorithms-91.Decode Ways
- [leetcode] 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- 91. Decode Ways
- leetcode 91. Decode Ways
- 91. Decode Ways
- 91. Decode Ways
- Leetcode 91. Decode Ways
- leetcode 91. Decode Ways
- LeetCode 91. Decode Ways
- 91. Decode Ways
- "围观"设计模式(7)--创建型之单例模式(Singleton Pattern)
- iOS 压力测试
- "围观"设计模式(8)--创建型之简单工厂模式、工厂方法模式、抽象工厂模式
- 静态初始化和实例初始化
- The 13th Zhejiang Provincial Collegiate Programming Contest-Defuse the Bomb(模拟)
- 91. Decode Ways
- select的onchange事件问题
- C++ OJ HDU 1243 反恐训练营
- ActionScript基本语法
- WebSocket至HelloWorld
- 微信公众平台、开放平台、智能平台区别
- xhr异步方法
- C++ OJ HDU 1159 Common Subsequence
- c++ primer(第五版)学习笔记及习题答案代码版(第一章)