LeetCode GrayCode
class Solution { public: vector<int> grayCode(int n) { vector<int> res; res.push_back(0); long pow2 = 1; for (int i=1; i <= n; i++) { int old_len = res.size(); for (int i=0; i<old_len; i++) { res.push_back(pow2 + res[old_len - i - 1]); } pow2<<=1; } return res; } };
再水一发, 不过n==0时,觉得应该返回一个空的vector
简化版:
class Solution { public: vector<int> grayCode(int n) { vector<int> res; res.push_back(0); for (int i=0; i<n; i++) { int idx = res.size() - 1; while (idx >= 0) { res.push_back(res[idx--] | 1<<i); } } return res; } };
递归方法:
class Solution { public: vector<int> grayCode(int n) { vector<int> res; if (n < 1) { res.push_back(0); return res; } else if (n == 1) { res.push_back(0); res.push_back(1); return res; } vector<int> sub = grayCode(n - 1); int len = sub.size(); for (int i=0; i < len; i++) { res.push_back(sub[i]); } for (int i=len-1; i>=0; i--) { res.push_back((1<<(n-1))|sub[i]); } return res; } };