Easy to understand Java


  • 0
    C

    From here: http://introcs.cs.princeton.edu/java/23recursion/

    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> result = new ArrayList<>();
            if (n <= 0) result.add(0);
            else gray("", n, result);
            return result;
        }
        
        private void gray(String prefix, int n, List<Integer> nums) {
            if (n == 0) {
                nums.add(Integer.parseInt(prefix, 2));
            } else {
                gray(prefix + "0", n - 1, nums);
                yarg(prefix + "1", n - 1, nums);
            }
        }
        
        private void yarg(String prefix, int n, List<Integer> nums) {
            if (n == 0) {
                nums.add(Integer.parseInt(prefix, 2));
            } else {
                gray(prefix + "1", n - 1, nums);
                yarg(prefix + "0", n - 1, nums);
            }
        }
    }

Log in to reply
 

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