您的位置:首页 > 其它

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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: