您的位置:首页 > 其它

LeetCode 89. Gray Code(生成格雷码)

2016-05-01 17:10 507 查看
public class Solution {
public List<Integer> grayCode(int n) {
int all = 1<<n;
List<Integer> result = new ArrayList<Integer>(all);//预分配空间
result.add(0);
if(n==0)return result;
result.add(1);
if(n==1)return result ;

int count = 2;
int index = 1;
int base = 2;
while(count<all){
if(index<0){
index = count-1;
base = base << 1;
}
result.add(base+result.get(index));
count++;
index--;
}
return result;
}
}


基本思路很简单:

假设有格雷码:a[0]=0,a[1]=1;接下来就是

a[2]=1a[1];a[3]=1a[0];(字符串拼接,不是乘法)

即把下一个最高位置为1,将目前有的格雷码倒序输出,加上最高位的1

这样使用O(n)的时间就能生成所有格雷码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: