Java recursive solution


  • 0
    O
    class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> res = new ArrayList<>();
            if (n < 0) {
                return res;
            } else if (n == 0) {
                res.add(0);
                return res;
            } else if (n == 1) {
                res.add(0);
                res.add(1);
                return res;
            }
            List<Integer> prev = grayCode(n - 1);
            for (int num : prev) {
                res.add(num);
            }
            for (int i = prev.size() - 1; i >= 0; i--) {
                res.add(prev.get(i) | (1 << n - 1));
            }
            return res;
        }
    }
    

Log in to reply
 

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