Share my simple recursive and iterative solution, Java


  • 0
    G

    public class Solution {

    // When we print the gray code backwards, the two successive values still differ in only one bit.

    public List<Integer> grayCode(int n) {
        List<Integer> result = new ArrayList<Integer>();
        if(n < 0){ return result;}
        if(n == 0){
            result.add(0);
            return result;
        }
        result = grayCode(n-1);
        int increment = (int) Math.pow(2, n-1);
        for(int i = result.size() - 1; i >= 0; i--){
            result.add(result.get(i) + increment);
        }
        return result;
    }
    

    }

    // iterative solution.

    public class Solution {

    public List<Integer> grayCode(int n) {
        List<Integer> result = new ArrayList<Integer>();
        if(n < 0){ return result;}
        result.add(0);
        for(int i = 1; i <= n; i++){
            int increment = (int) Math.pow(2, i-1);
            for(int j = result.size() - 1; j >= 0; j--){
                result.add(result.get(j) + increment);
            }
        }
        return result;
    }
    

    }


Log in to reply
 

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