[leetcode]Gray Code

不难。就是比如到了[0, 1, 3, 2]时,下一组就要[4+2, 3+2, 1+2, 0+2]。但是当时没有做到ans.add(0)一开始初始化(而是只放在n==0的判断block内了),所以runtime error了。看了半天看出来了。

public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<Integer> ans = new ArrayList<Integer>();
        ans.add(0);
        if (n == 0) {           
            return ans;
        }
        
        for (int i = 0; i < n; i++) {
            int m = (int)Math.pow(2, i);
            for (int j = m - 1; j >=0; j--) {
                ans.add(ans.get(j) + m);
            }
        }
        
        return ans;
    }
}

  

原文地址:https://www.cnblogs.com/lautsie/p/3256038.html