A Straight Solution in Java


  • 1
    H
    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> result = new ArrayList<Integer>();
            int size = (int) Math.pow(2, n);
            result.add(0);
            int base = 1;
            while (result.size() < size) {
                List<Integer> pre = new ArrayList<Integer>(result);
                for (int i = pre.size() - 1; i >= 0; i--) {
                    result.add(pre.get(i) ^ base);
                }
                base *= 2;
            }
            return result;
        }
    }

  • 0
    A

    @hunter.na That's an amazing solution,very neat.I had a less concise solution,yours was exactly how mine would be looking like if optimized.


Log in to reply
 

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