Decode Ways

来源:互联网 发布:淘宝标题栏素材 编辑:程序博客网 时间:2024/05/29 03:50
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.


解决方法:利用动态规划来做,设dp[i]为前i个数的译码方法,s[len]为字符串。
首先当len=0或者s[0]=0时,是不存在译码方法的;
dp[0]=0,
dp[i]=s[i-1]单独作为一个字母的译码方法+s[i-1]和s[i-2]一起作为一个字母的译码方法,1<=i<=len.

具体代码为:
class Solution {public:    int numDecodings(string s) {        int len=s.size();        int i,j,result;        int *dp=new int[len+1];        if(len==0||s[0]=='0')        return 0;        dp[0]=1;                for(i=1;i<=len;i++){            if(s[i-1]=='0')              dp[i]=0;            else               dp[i]=dp[i-1];            if(i>1&&(s[i-2]=='1'||(s[i-2]=='2'&&s[i-1]<='6')))              dp[i]+=dp[i-2];        }        result=dp[len];        delete []dp;        return result;    }};



原创粉丝点击