"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "
title Link: https://leetcode.com/problems/gray-code/
Test Instructions:give an n, you get an array that includes all n-bit gray codes
Ideas:first, we need to know how gray code came from.now we're going to get a 6 gray code.First we get 6 bits.Gray code is by adding a 0 in front of this binary, getting 0110, then two adjacent bits are XOR, get 101, so 6 of the Gray code is 5So now how do we ask 1~n all the numbers corresponding to the gray code? first of all, when N=10-0, 0-01-1, 1-1when the n=20, 0 , XX,1, 13 2->2 3->when the n=30, 01, 001, 001, 1 ,3, 011, 010, 2 ,2, 010, 011, 3 ,4, 67, 111, 101, 5 ,6, 101, 57, 111, 4
through the three groups we can see the law, when the current number of BITS is n, then this number corresponds to the number of 2^nThe number of front 2^ (n-1) is directly derived from the situation (n-1), and these numbers are based on the original added a 0, so gray code will not changeand Back 2^ (n-1) number is the first 2^ (n-1) number in front plus 1, and these trees are based on the previous 2^ (n-1) in the order of the number of reverse, and then each number plus 2^ (n-1) to get
Class Solution{public: vector<int> graycode (int n) { vector<int> A; A.push_back (0); if (n==0) return A; A.push_back (1); if (n==1) return A; int x = 1; for (int i = 2; i<=n; i++) { x*=2; int len = A.size (); for (int j = len-1; j>=0; j--) { a.push_back (a[j]+x); } } return A; };
Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source
[Leedcode OJ] #89 Gray Code