leetcode 89. Gray Code

来源:互联网 发布:linux服务器面板 编辑:程序博客网 时间:2024/05/19 17:24

题意

相连的两个数的二进制位只有一位不同。

题解

给数组中前面已有的数添加新的最高位(从后往前),保证任意两个数只相差一个。

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;    }}
0 0