My recursive solution

  • 0

    My idea is to group the one's and two's that are possibly contributing to extra ways of decoding. If we can count the length of all of the groups like "123" or "1212", then we simply multiply all of Fabonacci numbers to get the final result. For example, for "123641212", we find two groups "123" and "1212" and our result will be Fab(3)*Fab(4) = 15.

    int fab(int n) // computing Fabonacci numbers
        if(n<2) return 1;
        else return fab(n-1)+fab(n-2);
    int numDecodings(string s)
        if(s.size()==0 || s[0]=='0') return 0; //an empty string or a string with leading '0'
        int i=0;    
        int len=1;
        while(i+1<s.size() && (s[i]=='1' || (s[i]=='2' && s[i+1]<='6')))
            if (s[i+1]!='0') ++len;
            else --len; //if the next character is '0', the previous '1' or '2' should be excluded
            return fab(len)*numDecodings(s.substr(i+1));
            return fab(len);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.