LeetCode89 Gray Code 格雷碼生成
阿新 • • 發佈:2019-02-01
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<int> grayCode(int n) { if(n<0) return vector<int>(0); vector<int> ans; int sum = pow(2, n); for(unsigned int i=0; i<sum; i++) { ans.emplace_back(i^(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<Integer> grayCode(int n) {
List<Integer> rs=new ArrayList<Integer>();
rs.add(0);
for(int i=0;i<n;i++){
int size=rs.size();
for(int k=size-1;k>=0;k--)
rs.add(rs.get(k) | 1<<i);
}
return rs;
}