leetcode Decode Ways Divide and Conquer

来源:互联网 发布:oracle数据库入门书籍 编辑:程序博客网 时间:2024/06/05 05:33

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.


Direct DFS would result in TLE.  Using the method of divide and conquer could solve this problem. 

The code seems lengthy, just taking three situations into account as the initial values:

start > end : return 1

start == end && not '0' : 

start + 1 ==end && not '01' etc..

The following is the code :

class Solution { public:  bool isCharacter(string& s, int start, int end) {    int num = 0;    if (start > end)      return false;    else if (start == end) {      if (s[start] >= '1' && s[start] <= '9')        return true;      else         return false;    }    else if (start + 1 == end){      if (s[start] == '1' || (s[start] == '2' && s[end] <= '6'))        return true;      else        return false;    }  }  /*  void countways(string& s, int start) {    if (start >= s.length()) {      ++count;      return;    }    for (int i = 0; i <= 1; ++i) {      if (start + i < s.length() && isCharacter(s, start, start + i))        countways(s, start + i +1);    }  }  */  int countways(string& s, int start, int end) {    int count = 0;    if (start > end)      return 1;    else if (start == end) {      if (isCharacter(s, start, end))        ++count;      return count;    }    else if (start + 1 == end) {      if (isCharacter(s, start, end))        ++count;      if (isCharacter(s, start, start) && isCharacter(s, end, end))        ++count;      return count;    }        int mid = (start + end)/2;    int countl = countways(s, start, mid);    int countr = countways(s, mid+1, end);    count = countl * countr;    if (mid >= 0 && mid +1 <= end && isCharacter(s, mid, mid +1)) {      countl = countways(s, start, mid - 1);      countr = countways(s, mid + 2, end);      count += countl * countr;    }    return count;  }  int numDecodings(string s) {    // Note: The Solution object is instantiated only once and is reused by each test case.    if (s.length() == 0)      return 0;    int count = countways(s, 0, s.length()-1);      return count;  }};