A message containing letters from was A-Z
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 "
, it could be decoded as " AB "
(1 2) Or " L "
().
The number of ways decoding is "12"
2.
Ideas: The subject with recursion is not realized, it may be that the recursion is not written well, and finally in the online reference to write the dynamic programming code.
The idea is to judge whether the current value is 0, not 0 f[i] = f[i] + f[i-1];
Then the current value and the previous character can be composed of 26 or less of the loss, can this with f[i] = F[i] + f[i-2].
The specific code is as follows:
public class Solution {public int numdecodings (String s) { //dynamic plan tag int[] f = new int[s.length ()]; Char[] C = S.tochararray (); Boundary condition if (c.length = = 0) { return 0; } First element f[0] = c[0] > ' 0 '? 1:0; if (c.length = = 1) { return f[0]; } F[1] value is key, write bad, there will be various errors int k = c[0] > ' 0 ' && c[1] > ' 0 '? 1:0; F[1] = k + (c[0] = = ' 1 ' | | c[0] = = ' 2 ' && c[1] <= ' 6 '? 1:0); Iterate backwards for (int i = 2; i < c.length; i++) { if (C[i] > ' 0 ') {//first element greater than 0, add f[i] + = f[i-1]; } //Between 10-26 add two letters to form a case if (c[i-1] = = ' 1 ' | | (C[i-1] = = ' 2 ' && c[i] <= ' 6 ')) { F[i] + = F[i-2];} } return f[c.length-1];} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 91.Decode Ways (decoding mode) thinking and method of solving problems