题意
相连的两个数的二进制位只有一位不同。
题解
给数组中前面已有的数添加新的最高位(从后往前),保证任意两个数只相差一个。
dfs保证遍历了所有情况,但是不能保证上述条件,所以不使用dfs。
代码
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<Integer>();
result.add(0);
for(int i = 0; i < n; i++)
for(int j = result.size() - 1; j >= 0; j--)
result.add(result.get(j) + (1 << i));
return result;
}
}