Java solution with explanation


  • 2
    H
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<>();
        res.add(0);
        if (n == 0) return res;
        for (int i = 0; i < n; i++) {
            List<Integer> temp = new ArrayList<>();
            temp.addAll(res);
            for (int j = temp.size() - 1; j >= 0; j--) {
                res.add((1<<i) + temp.get(j));
            }
        }
        return res;
    }
    
    • 000
    • 001
    • 011
    • 010

    • 110
    • 111
    • 101
    • 100

    Think about how to get gray code when n is 3: the first 4 gray codes is the same with when n equals to 2, and the last gray codes is adding 1 in front of the gray codes when n is 2. The first 4 is symmetric to the last 4.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.