Gray Code
The gray code is a binary numeral system where the successive values are differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code . A Gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2] . Its gray code sequence is:
00-001-111-310-2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, was [0,2,3,1] also a valid gray code sequence according to the above definition.
For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.
https://leetcode.com/problems/gray-code/
Directly with the gray code conversion formula, move right one with itself or.
Use DFS to get answers that match test instructions, but the answer is only in the order of Gray Code, and the big data is timed out with DFS.
1 /**2 * @param {number} n3 * @return {number[]}4 */5 varGraycode =function(n) {6 varLen = Math.pow (2, n), res = [];7 for(vari = 0; i < Len; i++)8Res.push (i ^ (i >> 1));9 returnRes;Ten}
DFS, the order is not AC.
1 /**2 * @param {number} n3 * @return {number[]}4 */5 varGraycode_wa =function(n) {6 if(n = = 0)return[0];7 varI, map = [], visited = {}, Len = Math.pow (2, n);8 for(i = 0; i < n; i++)9Map[i] = 0;TenVisited[map.join ("")] =true; One returnDFS (map, [0]); A - functionDFS (map, res) { - if(Res.length = = =len) the returnRes; - varKey = "", TMP; - for(vari = 0; I < n; i++){ -Map[i] = = = 0? Map[i] = 1:map[i] = 0; +Key = Map.join (""); - if(!Visited[key]) { +Visited[key] =true; ARes.push (parseint (Key, 2)); atTMP =DFS (map, res); - if(TMP)returntmp; - Res.pop (); -Visited[key] =false; - } -Map[i] = = = 0? Map[i] = 1:map[i] = 0; in } - return false; to } +};
[Leetcode] [JavaScript] Gray Code