1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package com.demo.s89;
import java.util.ArrayList; import java.util.List;
public class Solution { public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>() {{ add(0); }}; int head = 1; for (int i = 0; i < n; i++) { for (int j = res.size() - 1; j >= 0; j--) res.add(head + res.get(j)); head <<= 1; } return res; } }
|