91. Decode Ways

来源:互联网 发布:经典数据新闻案例分析 编辑:程序博客网 时间:2024/05/20 01:36

题目:

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.


代码:

class Solution {public:    int numDecodings(string s) {        int n=s.size();        if(n==0) return 0;        vector<int> dp(n+1,0);        dp[0]=1;        for(int i=1;i<=n;i++){            if(s[i-1]!='0')   dp[i]+=dp[i-1];            if(i>1&&s[i-2]=='1') dp[i]+=dp[i-2];            if(i>1&&s[i-2]=='2'&&s[i-1]>='0'&&s[i-1]<='6') dp[i]+=dp[i-2];        }        return dp[n];    }};

笔记:

每一种情况对应dp[i]的一次叠加

原创粉丝点击