leetcode 89: Gray Code
2015-08-09 12:37
369 查看
class Solution { public: vector<int> grayCode(int n) { vector<int> res; map<int,bool> mp;//check whether a number is existed res.push_back(0); if(n==0) return res; mp[0]=1; vector<int> cal(n);//save as 1,2,4,8,... cal[0]=1; for(int i=1;i<n;i++) cal[i]=cal[i-1]*2; int num=0; int i=0; while(i<n) { int temp=num^cal[i]; if(mp.find(temp)==mp.end()) { mp[temp]=1; res.push_back(temp); num=temp; i=0; } else i++; } return res; } };
A simpler way to do it
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
res.push_back(0);
if(n==0)
return res;
int mask=1;
while(res.size()!=1<<n)
{
int len=res.size();
for(int i=len-1;i>=0;i--)
res.push_back(mask|res[i]);
mask=mask<<1;
}
return res;
}
};
相关文章推荐
- [POJ3070]Fibonacci
- h264: mp4 to annexb in ffmpeg
- GameBuilder见缝插针游戏开发系列(AA)
- UVA 10294 等价类计数
- iOS面试-1
- 二叉排序树(模板类)
- 如何提高自己的能力
- SVN的使用__[搬运工]
- android中画文字的换行 办法(对于遇到canvas.drawText(String s )无法实现换行问题的解决)
- libevent HTTP client 的实现
- wordpress 开源博客系统部署
- 第78讲:scala 中Type与Class初步学习
- android学习笔记(8)linearlayout与android:layout_weight学习
- Android中自定义属性(attrs.xml,TypedArray的使用)
- hbase client访问的超时时间、重试次数、重试间隔时间的配置
- QGIS相关网址
- 设计模式-单例模式
- Redis 5种数据类型,2种特殊数据处理策略
- 黑马程序员——Java GUI(图形用户界面)
- 如何阅读文献