public static ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        result.add(0);
        if (n == 0) {
            return result;
        }
        
        result.add(1);
        if (n <= 1) {
            return result;
        }
        
        for (int i = 2; i <= n; i++) {
            ArrayList<Integer> newresult = new ArrayList<Integer>();
            newresult.addAll(result);
            
            ArrayList<Integer> reversed = reverse(result);
            for (Integer ele : reversed) {
                newresult.add(ele + (1<<(i-1)));
            }
            result = newresult;
            //System.out.println(result.toString());
        }
        return result;
    }