【leetcode】Gray Code

来源:互联网 发布:mac怎升级flash插件 编辑:程序博客网 时间:2024/06/10 09:18

Gray Code

The gray code is a binary numeral system where two successive values 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:
这里写图片描述

网上学得到的代码,具体的思路就是下图:
这里写图片描述

class Solution {public:  vector<int> grayCode(int n) {    vector<int> result;    result.push_back(0);    for(int i=0;i<n;i++)    {        int highest=1<<i;        int length=result.size();        for(int j=length-1;j>=0;j--)        {            result.push_back(highest+result[j]);        }    }    return result;}
0 0