public List<Integer>grayCode(int n){
List<Integer> res =newArrayList<>();
res.add(0);for(int i =1; i <= n; i++){//要加的数int x =1<<(i -1);for(int j = res.size()-1; j >=0; j--){// res.get(j) | x 等价于 res.get(j) + x
res.add(res.get(j)| x);}}return res;}
go
funcgrayCode(n int)[]int{var res []int
res =append(res,0)for i :=1; i <= n; i++{//要加的数
x :=1<<(i -1)for j :=len(res)-1; j >=0; j--{// res[j]|x 等价于 res[j]+x
res =append(res, res[j]|x)}}return res
}
题目链接思路格雷码简介初始化一个返回值res第一个整数是0;n位的格雷码就需要构建n次将之前的解照搬过来然后倒序把每个数加上1<<(n-1)添加到res中即可构建完成返回resjavapublic List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<>(); res.add(0); for (int i = 1; i <= n;