Leetcode: Decode Ways
I. Question
A given string contains 26 letters, which are mapped to numbers, for example:
'A' --> 1
'B' --> 2
...
'Z' --> 26
How many encoding methods are provided for a string of numbers?
* Note: '12' can be encoded as "AB" or "L ".
Ii. Analysis
It can be seen that the purpose of the question is to investigate the dynamic planning, that is, there may be two situations in each step. Is it similar to crawling steps? Yes.
There are two ideas for this question, but they are the same:
1. Traverse from front to back
(1), ans [0] = 1;
(2) If s [0] = '0', ans [1] = 0; otherwise, ans [1] = 1;
(3) traverse judge s [I-1] is equal to '0', 0 ans [I] = 0; otherwise it is equal to ans [I-1], then judge whether or not the number with the next digit is greater than 26, less than then ans [I] = ans [I] + ans [I-2]
2. Traverse from the back to the front
(1), ans [len] = 1;
(2) If s [len-1] = '0', ans [len-1] = 0; otherwise ans [len-1] = 1;
(3) traverse to determine whether s [I] is equal to '0', and if it is 0, continue; otherwise, judge whether the number of the next digit is greater than 26, otherwise, ans [I] = ans [I + 1]. Otherwise, ans [I] = ans [I + 1] + ans [I + 2]
1. Forward traversal:
class Solution {public: int numDecodings(string s) { int len = s.size(); if(len == 0) return 0; int ans[len+1]; ans[0] =1; if(s[0] != '0') ans[1] = 1; else ans[1] = 0; for(int i=2;i<=len;i++){ if(s[i-1] != '0') ans[i] = ans[i-1]; else ans[i] = 0; if(s[i-2] == '1'||(s[i-2] == '2' && s[i-1] <= '6')) ans[i] = ans[i] + ans[i-2]; } return ans[len]; }};
2. Reverse traversal:
class Solution {public: int numDecodings(string s) { int len = s.size(); if(len == 0) return 0; int ans[len+1]; memset(ans,0,len*sizeof(int)); ans[len] =1; if(s[len-1] != '0') ans[len-1] = 1; else ans[len-1] = 0; for(int i=len-2;i>=0;i--){ if(s[i] == '0') continue; if(s[i] > '2'||(s[i] == '2' && s[i+1] > '6')) ans[i] = ans[i+1]; else ans[i] = ans[i+1] + ans[i+2]; } return ans[0]; }};