LeetCode : Decode Ways

来源:互联网 发布:淘宝线下实体店加盟费 编辑:程序博客网 时间:2024/05/16 10:46

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.

Solution:

DP,

total(i) = total[i-1] + end_with[i - 1];

end_with[i] = total[i  -1 ];

where end_with[i ] means the number of ways to decoding with s[i] alone to be a letter.

class Solution {public:    int numDecodings(string s) {    // Start typing your C/C++ solution below// DO NOT write int main() functionif(s.empty()){return 0;}int count = 0;vector<int> total(s.size());vector<int> end_with(s.size());char ch = s[0];if(ch > '0'){total[0] = 1;end_with[0] = 1;}for(int i = 1; i< s.size(); ++i){if(s[i] > '0'){end_with[i] = total[i-1];total[i] = total[i -1];}int num = atoi(s.substr(i-1, 2).c_str());if (num > 0 && num <=26){total[i] += end_with[i-1];}}return total[s.size() - 1];}};


今天做的时候有想到了一个更清晰的方法。

dp[i] = dp[i-1] + dp[i-2]

class Solution {public:    int numDecodings(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int n = s.size();        if(n == 0) return 0;        vector<int> res(n + 1, 0);        res[0] = 1;        if(s[0] != '0')            res[1] = 1;        string temp;        for(int i = 1; i< n; ++i){            temp = s.substr(i-1, 2);            int value = atoi(temp.c_str());            if(s[i] != '0')                res[i+1] = res[i];            if(value > 9 && value < 27){                res[i+1] += res[i-1];            }        }        return res[n];    }};


原创粉丝点击