Leetcode Decode Ways

来源:互联网 发布:虚航软件 编辑:程序博客网 时间:2024/06/07 05:55

Leetcode Decode Ways 相关代码。本题是一个典型的dp题,本算法使用cpp实现,如下。

#include <iostream>#include <string>#include <vector>using namespace std;// Every element has two method to resolve.// -- The first is combined with the former one, which need the former cannot combine which// the one before it, and the number of method equals to the str[0:i-2].// -- The second is current one isolated, which means the former one can either combine with// the one before it or not, and the number of method equals to the str[0:i-1].// So, the result is the sum of the two.class Solution {public:    int numDecodings(string s) {        if (s.length() == 0 || s[0] == '0') {            return 0;        }        int len = s.length();        vector<int> re(len, 0);        re[0] = 1;        for (int i = 1; i < len; i ++) {            // It should not contain continuous '0'            if (s[i - 1] == '0' && s[i] == '0') {                return 0;            }            if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6')) {                if (i >= 2) {                    re[i] += re[i - 2];                } else {                    re[i] += 1;                }            }            if (s[i] != '0') {                re[i] += re[i - 1];            }        }        return re[len - 1];    }};int main(int argc, char * argv[]) {    Solution so;    string test("27");    int re = so.numDecodings(test);    cout<<"num:"<<re<<endl;    return 0;}
0 0