91. Decode Ways

91. Decode Ways

题目

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]取决于dp[i-1]和dp[i-2];然后dp[0]的初始化
// 91. Decode Ways
class Solution_91 {
public:
    // 限制条件,比如说一位数时不能为0,两位数不能大于26,其十位上的数也不能为0
    int numDecodings(string s) {
        if (s.empty() || (s.size() > 1 && s[0] == '0'))
            return 0;
        vector<int> dp(s.size()+1,0); //表示前i个字符的解码方式
        dp[0] = 1;  
        for (int i = 1; i <= s.size();i++)
        {
            if (s[i-1]!='0') //i-1位置不为0,可以独立一种出来
            {
                dp[i] += dp[i - 1];
            }
            if (i>1 && (s[i - 2] == '1' || (s[i - 2] == '2'&& s[i - 1]>='0'&& s[i - 1] <= '6'))) //根据i-2的位置
            {
                dp[i] += dp[i - 2];
            }
        }
        return dp[s.size()];
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8807979.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞