https://leetcode-cn.com/probl...我自己写了第一个方法,然后总结了解决方案中看到的两个方法搜索类解决方案:defgrayCode(self,n:int)->List[int]:f=[False]*(2**n)f[0]=Truer=[0]defdfs(x):iflen(r)==2**n:returncur=1foriinrange(n):ifx&cur:ifnotf[x-cur]:f[x-cur]=Truer.append(x-cur)dfs(x-cur)返回else:ifnotf[x|cur]:f[x|cur]=Truer.append(x|cur)dfs(x|cur)returncur<<=1dfs(0)returnr镜像方式来自题解https://leetcode-cn.com/probl...n+1的答案就是把n的答案复制两份,一份上一份下放在一起,最上面的最高位补0(其实就是保留不变),最下面的最高位补1,顺序倒过来。类解决方案:defgrayCode(self,n:int)->List[int]:ifn==0:returnn[0]如果n==1:返回[0,1]r=self.grayCode(n-1)returnr+[r[i]+(1<
