Share my simple and easy to understand Java solution


  • 0
    N
    public List<Integer> grayCode(int n) {
        List<Integer> result = new ArrayList<>();
        result.add(0);
        int current = 0;
        int maskPos = 0;
        while (maskPos < n) {
            current ^= 1 << maskPos;
            if (!result.contains(current)) {
                result.add(current);
                //return the mask position to 0
                maskPos = 0;
            } else {
                // revert the change
                current ^= 1 << maskPos;
                // try next position
                maskPos++;
            }
        }
        // all position tried, no more result added, return result
        return result;
    }
    

Log in to reply
 

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