zoukankan      html  css  js  c++  java
  • [Leetcode] Decode Ways

    Decode Ways 题解

    题目来源:https://leetcode.com/problems/decode-ways/description/


    Description

    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.

    Example

    Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

    The number of ways decoding "12" is 2.

    Solution

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

    解题描述

    这道题题意是,给出一个数字串,求数字串能解码出多少种字母序列。这里给出的是DP的解法,其中关键就是求出可能会有2种情况的解码方式。讨论区给出的详细的解释是:

    • 给出例子123XXXX
    • 1这个位置上,向前探1位可以构成12,符合解码字符要求
    • 这样12可以被拆分为1 212,记1所在位置为i
      • 1 2而言,前面的解码方法对应从2开始的解法,有dp[i + 1]
      • 12而言,前面的解码方法对应从3开始的解法,有dp[i + 2]
    • 所以dp[i] = dp[i + 1] + dp[i + 2]
  • 相关阅读:
    VS2013安装与部署工具中添加 vcredist_x64.exe
    ZeroMQ高水位标记(high-water mark,HWM)
    Ubuntu16.04 动态链接库(.so)查询路径设置
    ubuntu16.04开机启动字符界面
    python 全局搜索路径
    learning to rank
    数据集
    hadoop streaming 文档
    机器学习:一些感想
    矩阵分解 推荐
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8372203.html
Copyright © 2011-2022 走看看