您的位置:首页 > 其它

【一天一道LeetCode】#91. Decode Ways

2016-06-13 23:38 417 查看

一天一道LeetCode


本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处



(一)题目


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.

(二)解题

题目大意:1~26代表A~Z,给定一串数字,求出能解码出多少种不同的结果。

解题思路:采用动态规划,从后往前,状态转移方程是:dp
= dp[n+1]+dp[n+2].

例如:123,从后往前算,3一种,23两种,123就是1+2三种,

当然要考虑很多特殊情况,如230,227,012等等

class Solution {
public:
int numDecodings(string s) {
int len = s.length();
if(len==0) return 0;
vector<int> df(len,-1);
int num = dfsNumDecWays(s,0,df);
return num;
}
int dfsNumDecWays(string &s , int idx , vector<int>& df)
{
int num1= 0;
int num2=0;
if(idx>=s.length()){//越界了就返回1
return 1;
}
if(df[idx]!=-1) //代表没有访问到
{
return df[idx];
}
if(s[idx]>='1'&&s[idx]<='9') {
num1 = dfsNumDecWays(s,idx+1,df);//求dp[n+1]
if(idx+1<s.length())
{
int temp = (s[idx]-'0')*10+s[idx+1] -'0';
if(temp>=1&&temp<=26)
{
num2=dfsNumDecWays(s,idx+2,df);//求dp[n+2]
}
}
}
df[idx] = num1+num2;//状态转移方程
return num1+num2;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: