My Java 1ms recursive solution


  • 0
    S
    public class Solution {
      List<Integer> res;
      public List<Integer> grayCode(int n) {
        res = new ArrayList<Integer>();
        res.add(0);
        for (int i = 0; i < n; i++) {
          int base = res.get(res.size()-1) | 1<<i;
          helper(base, i);
        }
        return res;
    }
    	
    private void helper(int base, int i) {
      if (i-- == 0 ) {res.add(base); return;}
        helper(base, i);
        helper(res.get(res.size()-1) ^ 1<<i, i);
      }
    }
    

Log in to reply
 

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