DP Solution in Java


  • 0
    M

    Since the Gray Code sequence for n = i can be fully determined by n = i - 1, we can solve in a DP manner.

    List<Integer> grayCode(int n) {
        List<Integer> result = new ArrayList<>(Arrays.asList(0));
        int base = 1;
        for (int i = 1; i <= n; i++, base <<= 1)
            for (int j = result.size() - 1; j >= 0; j--)
                result.add(result.get(j) + base); 
        return result;
    }
    

Log in to reply
 

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