首页 > 动态规划 > 线性DP > LeetCode-Decode Ways[动态规划]
2014
11-18

LeetCode-Decode Ways[动态规划]

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.

标签: Dynamic Programming String
分析

跟 Climbing Stairs (见 \S \ref{sec:climbing-stairs})很类似,不过多加一些判断逻辑。

代码1

// LeetCode, Decode Ways
// 动规,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
    int numDecodings(const string &s) {
        if (s.empty() || s[0] == '0') return 0;

        int prev = 0;
        int cur = 1;
        // 长度为n的字符串,有 n+1个阶梯
        for (size_t i = 1; i <= s.size(); ++i) {
            if (s[i-1] == '0') cur = 0;

            if (i < 2 || !(s[i - 2] == '1' ||
                     (s[i - 2] == '2' && s[i - 1] <= '6')))
                prev = 0;

            int tmp = cur;
            cur = prev + cur;
            prev = tmp;
        }
        return cur;
    }
};

Java代码:

public class Solution {
    public int numDecodings(String s) {
        if(s.length() == 0) return 0;
        if(s.charAt(0) == '0') return 0;
        if(s.length() == 1) return s.charAt(0) > '0' ? 1:0;
        int dp[] = new int[s.length()+1];
        dp[0] = dp[1] = 1;
        for(int i=2; i<=s.length(); i++){
            dp[i] = dp[i-1];
            if(s.charAt(i-1) == '0')
                if (s.charAt(i-2) == '1' || s.charAt(i-2) == '2')
                    dp[i] = dp[i-2];
                else return 0;
            else if(s.charAt(i-2) == '0'){
                dp[i] = dp[i-1];
                continue;
            }
            else if(s.charAt(i-2) < '2' || (s.charAt(i-2) == '2' && s.charAt(i-1) < '7') )
                dp[i] += dp[i-2];
        }
        return dp[s.length()];
    }
}

  1. 第二种想法,我想来好久,为啥需要一个newhead,发现是把最后一个节点一直返回到嘴上面这层函数。厉害,这道题之前没样子想过。