A 10-line java solution with explanation


  • 0
    T

    0: 0
    1: 0 || 1
    2: 0 1 || 11 10
    3: 0 1 11 10 || 110 111 101 100
    Add 1 bit in front of each number in the existing list in reverse order.

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

Log in to reply
 

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