LeetCode-Gray Code

看懂题目后非常简单,

找到规律就比较好写了,

如果已经有最低k位的格雷码了的话,

只需要把k+1位变成1,然后和前面k位的格雷码组合在一起就行了,

这时候前k位格雷码的顺利要倒过来;

 1 class Solution {
 2 public:
 3     vector<int> grayCode(int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<int> res;
 7         if (n <= 0) {
 8             return res;
 9         }
10         res.push_back(0);
11         res.push_back(1);
12         get(res, 1, n);
13         return res;
14     }
15     void get(vector<int> &res, int k, int n) {
16         int high = 1 << k;
17         while (k < n) {
18             int prelen = res.size();
19             for (int i = prelen - 1; i >= 0; --i) {
20                 int temp = high + res[i];
21                 res.push_back(temp);
22             }
23             ++k;
24             high <<= 1;
25         }
26     }
27 };
原文地址:https://www.cnblogs.com/chasuner/p/graycode.html