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]
  • 相关阅读:
    ILockBytes Windows Mobile 6.5
    C# 中 in,out,ref 的作用与区别
    riched32.dll riched20.dll msftedit.dll 解析
    C# 解决窗体假死的状态
    testform
    ParallelProgramming-多消费者,多生产者同时运行并行
    C# 多线程控制 通讯
    C# 多线程
    iSpy免费的开源视频监控平台
    核心J2EE模式
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8372203.html
Copyright © 2011-2022 走看看