Decode ways
A message containing letters fromA-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 cocould be decoded"AB"
(1 2) or"L"
(12 ).
The number of ways Decoding"12"
Is 2.
Thoughts: dynamic planning, analysis:
12121212: the front is 1 or (the front is 2 and the current value <7): F (n) = f (n-1) + f (n-2 );
1202: The current value is 0, followed by 1 or 2, F (n) = f (n-2). Otherwise, return 0.
In other cases, F (n) = f (n-1 );
Class solution {public: int numdecodings (string s) {int n = S. size (); If (n = 0 | s [0] = '0') return 0; vector <int> F (n + 1 ); f [0] = f [1] = 1; for (INT Index = 2; index <= N; ++ index) {If ('0' = s [index-1]) {If ('1' = s [index-2] | '2' = s [index-2]) f [Index] = f [index-2]; else return 0 ;} else if ('1' = s [index-2] | ('2' = s [index-2] & S [index-1] <'7' )) f [Index] = f [index-1] + F [index-2]; else f [Index] = f [index-1];} return f [N] ;}};
Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integerNRepresenting the total number of BITs in the code, print the sequence of Gray code. A gray code sequence must begin with 0.
For example, givenN= 2, return[0, 1, 3, 2]
. Its Gray code sequence is:
00-001-111-310-2
Note:For a givenN, A gray code sequence is not uniquely defined.
For example,[0, 2, 3, 1]
Is also a valid Gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of Gray code sequence. Sorry about that.
Thought: The method is clever. Each time a loop is changed, only the highest bit 0-> 1 is changed.
Class solution {public: vector <int> graycode (int n) {vector <int> VEC (1, 0); For (INT I = 0; I <N; ++ I) {int v = 1 <I; for (Int J = Vec. size ()-1; j> = 0; -- j) Vec. push_back (VEC [J] + V);} return VEC ;}};
44. Decode Ways & Gray Code