Simple to understand 1 ms Java solution


  • 0
    T
    public class Solution {
        public List<Integer> grayCode(int n) {
            
            int mask = 1<<n;
            List<Integer> list = new ArrayList<Integer>();
            for(int i = 0;i<mask;i++){
                list.add( generateNth(i) );
            }
            return list;
        }
        
        public int generateNth(int num){
            return num^(num/2); //logic to generate nth gray code sequence. Try it out yourself to know why it works
        }
    }

Log in to reply
 

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