/*本题由两种方法:1)直接根据格雷码的公式进行求解(这个可以参考最下面的网址);
2)根据题目定义,n位的格雷码可以根据n-1位的格雷码生成(在每个数字前添加数字0
或者数字1)。
此处代码采用方法2)。
方法参考自: https://github.com/soulmachine/leetcode*/
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
res.reserve(1 << n);
res.push_back(0);
for(int i = 0; i < n; ++i){
const int highest_bit = 1 << i;
for(int j = res.size()-1; j >= 0; --j){
res.push_back(highest_bit | res[j]);
}
}
return res;
}
};
LeetCode之Gray Code
最新推荐文章于 2019-09-20 21:04:01 发布