There is a map,key from A to Z, and the corresponding value is from 1 to 26, for example:
A = 1
b = 2
...
Z = 26, for a number string "11", can be a combination of "AA" corresponding to the number of "K" corresponding to the number of the corresponding combination of 2; Similarly, for example, "111" corresponds to the number of combinations is 3, respectively, "AAA", "Ka", "ak".
Given a number array, the corresponding number of combinations is calculated.
Answer: For a string, define f (x) as the number of combinations of the first X characters, then:
f (x) = f (x-2) if the last digit is ' 0 '
= f (x-1) else if (the penultimate number is ' 0 ' | | The last two numbers are greater than "26")
= f (x-1) +f (x-2) Else
intLast2num (Char* Arr,intLen) {Assert (arr! = NULL && len >=2); intnum = (arr[len-2]-'0')*Ten+ (arr[len-1]-'0'); if(Num <= -) return 2; Else return 1;}intCountkind (Char* Arr,intLen) { if(arr = = NULL | | Len <=0) return 0; if(len = =1) return 1; if(len = =2) { if(arr[len-1] =='0'|| Last2num (arr, len) > -) return 1; Else return 2; } if(arr[len-1] =='0') returnCountkind (arr, len-2); Else if(arr[len-2] =='0'|| Last2num (arr, len) > -) returnCountkind (arr, len-1); Else returnCountkind (arr, len-1) + Countkind (arr, len-2);}
Another way to do this:
The recursion used above, Countkind has repeated calculation, one method is to save the computed in an array, calculate is to check, if counted, directly return the result; Another method is to calculate from 0, the code is as follows:
intLast2num (Char* Arr,intLen) {Assert (arr! = NULL && len >=2); return Ten* (arr[len-2]-'0') + (arr[len-1]-'0');}intCountkind (Char* Arr,intLen) { if(arr = = NULL | | Len <=0) return 0; if(len = =1) return 1; Else if(len = =2) { if(arr[len-1] =='0'|| Last2num (arr, len) > -) return 1; Else return 2; } intcnt[len+1]; cnt[0] =0; cnt[1] =1; if(arr[1] =='0'|| Last2num (arr,2) > -) cnt[2] =1; Elsecnt[2] =2; for(inti =3; i < Len; i++) { if(arr[i-1] =='0') Arr[i]= arr[i-2]; Else if(arr[i-2] =='0'|| Last2num (arr,2) > -) Arr[i]= arr[i-1]; ElseArr[i]= arr[i-1] + arr[i-2]; } returnArr[len];}
A separate calculation of length equal to 2 is necessary in order to solve a case like "70".
Number of combinations of strings