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

你可能感兴趣的:(java,LeetCode)