A simple Java solution with explanation


  • 0
    L

    If you look at the sequence, there is no particular pattern you need to follow. It means that you will be backtracking checking every condition. A more predictable is to note that the solution to a number n is based on the solution of n-1 prepended with '0' and then '1' in reverse order of sequence. Here is the code:

       public List<Integer> grayCode(int n) {
            List<String> list = helper(n);
            List<Integer> ret = list.parallelStream().map((x)->Integer.parseInt(x,2)).
                collect(Collectors.toList());
            return ret;
            
        }
        
        public List<String> helper(int n) {
            if(n==0) {
                return Arrays.asList("0");
            }
            else if(n==1) {
                return Arrays.asList("0","1");
            }
            List<String> ll = helper(n-1);
            
            List<String> another = new ArrayList<>();
            for(int i=0;i<ll.size();i++) {
                another.add('0'+ll.get(i));
            }
            for(int i=ll.size()-1;i>=0;i--) {
                another.add('1' + ll.get(i));
            }
            return another;
        }
    

Log in to reply
 

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