LintCode:格雷码
2016-04-24 22:21
309 查看
LintCode:格雷码
The tricky part of this question is to recognize the recursive structure here. For n = 0, sol = [0], that’s the base case. For recursive step, let’s take n = 2 and n = 3 as examples. n = 2, sol = [0, 1, 3, 2]; n = 3, sol = [0, 1, 3, 2, 6, 7, 5, 4]. Look at these two solutions, we see when n = 3, we add 4 more elements [6, 7, 5, 4] and they are just [2+4, 3+4, 1+4, 0+4]. That is sol(n+1) = sol(n) + [ reverse(sol(n)) + 2^(n) ].
The tricky part of this question is to recognize the recursive structure here. For n = 0, sol = [0], that’s the base case. For recursive step, let’s take n = 2 and n = 3 as examples. n = 2, sol = [0, 1, 3, 2]; n = 3, sol = [0, 1, 3, 2, 6, 7, 5, 4]. Look at these two solutions, we see when n = 3, we add 4 more elements [6, 7, 5, 4] and they are just [2+4, 3+4, 1+4, 0+4]. That is sol(n+1) = sol(n) + [ reverse(sol(n)) + 2^(n) ].
class Solution: # @param {int} n a number # @return {int[]} Gray code def grayCode(self, n): # Write your code here L = [0] m = 0 while len(L) < pow(2, n): L += [pow(2, m) + i for i in L[::-1]] m += 1 return L
相关文章推荐
- jQuery笔记-事件
- 分布式之高性能组件
- MFC弹出对话框之前先进行条件判断以决定是否弹出对话框
- Win7安装Office2010时提示需要安装MSXML 6.10.1129.0
- 第八章类的高级概念
- 1011-Oil Deposits
- 绘制直方图以及均衡化处理
- 趣味素数-梅森尼数-java
- 作业——在线学习Android课程之第八周(下载器)
- Swift中常用的数据类型
- 内存分布和栈空间---Memory Layout And The Stack
- Android:Layout_weight的深刻理解
- 2016-04-24博客首开纪念
- 学习进度条8
- Builder(生成器)-对象创建型模式
- Java中处理异常throw和throws
- 开源项目smartImageView
- 一个算法题目的两种不同效率级别的算法对比
- static
- [改善Java代码]使用package-info类为包服务