Java simple solution


  • 0
    M
     public static ArrayList<Integer> grayCode(int n) {
            ArrayList<Integer> res=new ArrayList<Integer>();
            if(n<=0)
            {
            	res.add(0);
            	return res;
            }
            if(n==1){
                res.add(0);
                res.add(1);
                return res;
            }
            
            ArrayList<Integer> temp=new ArrayList<Integer>();
            temp=grayCode(n-1);
            res=grayCode(n-1);
            Collections.reverse(temp);
            for(int i=0;i<temp.size();i++){
              res.add((int)(temp.get(i)+Math.pow(2,n-1)));  
            }
            
            return res;
        }

Log in to reply
 

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