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)的時間就能生成所有格雷碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章