LeetCode#91. Decode Ways

topic:

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.

Analysis of the meaning:

The idea of ​​dynamic programming can be used to solve the problem. English letters can be mapped to 1 to 26 numbers. Let F(n) represent how many decoding methods there are for n numbers, and a[] is the input string of numbers, then we can to the following recursion formula.

若a[n] != 0,且 (a[n-1]*10+a[n] >= 1 && a[n-1]*10+a[n] <= 26)   F(n) = F(n-1)+F(n-2);

若a[n] != 0, 且 (a[n-1]*10+a[n] == 0 || a[n-1]*10+a[n] > 26)  F(n) = F(n-1);

若a[n] == 0,且 (a[n-1]*10+a[n] >= 1 && a[n-1]*10+a[n] <= 26)   F(n) = F(n-2);

若a[n] == 0, 且 (a[n-1]*10+a[n] == 0 || a[n-1]*10+a[n] > 26)  F(n) =0;

From the above recursive formulas, the correct result can be obtained, and finally F(n) can be output.

A C++ implementation is as follows:

#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
    int numDecodings(string s) {
        int num = s.length();
        if(num == 0) return 0;
        if(s[0] == '0') return 0;
		int *res = new int[num+1];
		res[0] = 1;
		res[1] = 1;
		for(int i = 1; i < num; i++) {
			string temp;
			temp = s.substr(i-1,2);
			if(isvalid2(temp) && isvalid1(s[i])) {
				res[i+1] = res[i]+res[i-1];
			} else if(isvalid2(temp) && !isvalid1(s[i])) {
				res[i+1] = res[i-1];
			} else if(!isvalid2(temp) && isvalid1(s[i])) {
				res[i+1] = res[i];
			} else {
				res[num] = 0;
				break;
			}
		}  
		return res[num];
    }
    //Check if a number is valid
    bool isvalid1(char s) {
    	if(s == '0') {
    		return false;
		} else {
			return true;
		}
	}
    //Check if two numbers are valid
	bool isvalid2(string s) {
		if(s[0] == '0') {
			return false;
		}
		int n;
		n = (s[0]-'0')*10 + (s[1]-'0');
		if(n > 26) return false;
		return true;
	}
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325401582&siteId=291194637