当前位置: 首页 > 后端技术 > Python

leetcode89.格雷码格雷码

时间:2023-03-25 19:56:17 Python

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<>1)^iclass解法:defgrayCode(self,n:int)->List[int]:return[(i>>1)^iforiinrange(2**n)]欢迎来到我的博客:https://codeplot.top/我的博客分类:https://codeplot.top/类别/%E5%88%B7%E9%A2%98/