LeetCode89 Gray Code 格雷码生成

1、十进制序列直接得到格雷码 参考:https://www.cnblogs.com/logic3/p/5609919.html

 binary num             gray code
 0=000      000 = 000 ^ (000>>1)
 1=001      001 = 001 ^ (001>>1)
 2=010      011 = 010 ^ (010>>1)
 3=011      010 = 011 ^ (011>>1)
 ...
 7=111      100 = 111 ^ (111>>1)

class Solution {
public:
    vector grayCode(int n) {
        if(n<0) return vector(0);
        
        vector ans;
        int sum = pow(2, n);
        for(unsigned int i=0; i>1));
        }
        
        return ans;
    }
};

2、My idea is to generate the sequence iteratively. For example, when n=3, we can get the result based on n=2.
00,01,11,10 -> (000,001,011,010 ) (110,111,101,100). The middle two numbers only differ at their highest bit, while the rest numbers of part two are exactly symmetric of part one. It is easy to see its correctness.
Code is simple:

public List grayCode(int n) {
    List rs=new ArrayList();
    rs.add(0);
    for(int i=0;i=0;k--)
            rs.add(rs.get(k) | 1<

 

你可能感兴趣的:(C++)