1. 程式人生 > >演算法:解碼方法(動態規劃)—— decode-ways(Dynamic programming)

演算法:解碼方法(動態規劃)—— decode-ways(Dynamic programming)

problem:

A string “s” is consisted of number characters. If thesubstring value of one or two adjacent characters in “s” is between 1 and 26,the substring can be converted to an alphabet. The rule is set as follows: “1”is converted to “A”, “2” to “B”, “3” to “C” ... and ”26” to “Z”. Please findout how many different results can string “s” be converted to.

(there is no corresponding letter to “0”)

Example:

Input: s=”123”

The results canbe: ”ABC”, “LC”, “AW”          (“23” to “W”,“12” to “L”)

Output: 3

Understandingand solving ideas

This problem isa one-dimensional problem, under normal circumstances is better to solve theproblem is that it is a reverse order of the problem, from the back push, dp[i] from the i-bit to the last one can be converted to the type Number, so dp[0] is the answer we ultimately need.

The next keypoint is the recursive derivation. According to the subject requirements, ifstr [i] is 0, there is no way to convert to letters, then dp [i] = 0; Then seestr [i] and str [i + 1] can form a letter, , Then dp [i] = dp [i + 1] + dp [i +2]; if not, then dp [i] = dp [i + 1].


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


int char2int(char c)
{
 return (c - '0');
}


int numDecodings(string s)
{
    if((s.empty())|| (s.length() == 0)|| (s[0] == '0'))
    {
         return 0;
    }

    if(s.length()==1)
    {
    if(s[0] != '0')
        return 1;
      else
        return 0;
    }
//dp[i]存放s[0]到s[i]所代表的個數 = int [s.length()]
	int dp[s.length()];

	int i;
	for(i=0;i<s.length();i++)
	  dp[i]=0;

	dp[0] = 1;
	dp[1] = (s[1] != '0' ? 1 : 0) + ((char2int(s[0]) * 10 + char2int(s[1])) <= 26 ? 1 : 0);
	for(int i = 2;i < s.length();i++)
    {
        if(s[i] != '0') //
            dp[i] += dp[i-1];
        if(s[i-1] != '0' && (char2int(s[i-1]) * 10 + char2int(s[i]) <= 26))
            dp[i] += dp[i-2];
    }
    return dp[s.length()-1];
}

int main()
{
	string s = "23143";

	cout << numDecodings(s) << endl;
	return 0;
}