Leetcode89. Gray Code

开始想的暴力解法,dfs一下,但是觉得不够简洁,应该是有简洁的方法的。一看discuss果然:
方法一:正常思路,找规律
观察:
n=2: 00,01,11,10
n=3: (000,001,011,010),(110,111,101,100)
可以看出,我们可以由n-1得到n,方法就是,前面的不变(前头加0的话对应的数是不变的),然后中心对称一下,在前面加1。

class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> ans = new ArrayList<>();
        if(n<0) return ans;
        ans.add(0);
        for(int i=0;i<n;i++){
            int size = ans.size();
            for(int j=size-1;j>=0;j--){
                ans.add(ans.get(j)|1<<i);
            }
        }
        return ans;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Gray Code.
Memory Usage: 33 MB, less than 100.00% of Java online submissions for Gray Code.

方法二:异或神操作:

class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> ans = new ArrayList<>();
        for(int i=0;i<1<<n;i++) ans.add(i^(i>>1));
        return ans;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Gray Code.
Memory Usage: 32.9 MB, less than 100.00% of Java online submissions for Gray Code.
不要问为什么,问就是找规律= =。反正目前我就是理解到这个是正好符合规律的。

posted @ 2019-04-23 10:38  大胖子球花  阅读(76)  评论(0)    收藏  举报