89.Gray Code

https://leetcode.com/problems/gray-code/discuss/29891/

https://leetcode.com/problems/gray-code/discuss/29882/

Learn How to Solve

class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> ans = new ArrayList<>();
        ans.add(0);
        for(int i = 1; i<= n; i++){
            int lastRoundSize = ans.size();
            for(int j = lastRoundSize - 1; j >=0; j--){
                int newVal = ans.get(j) | (1 << (i - 1));
                ans.add(newVal);
            }
        }
        return ans;
    }
}

results matching ""

    No results matching ""