1ms JAVA solution O(1) space and O(n) time


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

Log in to reply
 

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