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

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)的时间就能生成所有格雷码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值