力扣89.格雷编码

题目:biubiu
题意:希望得到一个序列,然后要求:
力扣89.格雷编码_第1张图片
这种题第一种想法就是找到一种符合所有条件的规则,然后没有找到,还是看的别人的题解。

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Solution {
public:
		vector<int> grayCode(int n) {
			vector<int> ans(1, 0);// 当 n 等于 0 的时候只有一个数字
			while (n--) {
				for (int i = ans.size() - 1; i >= 0; i--) {
					// 轴对称过去
					//cout << ans[i] <<"#"<
					ans[i] *= 2; // 每一个数字乘二,相当于前一半数字末尾补上 0
					//cout << ans[i] << "*" << endl;
					ans.push_back(ans[i] + 1); // 后半部分补上 1,相当于 把这个数字乘以 2 加上一 
				}
			/*for (const auto& p : ans)
					cout << p << "-";
				cout << endl;*/
			}
			return ans;
		}

};

int main() {
	int n;
	while (cin >> n) {
		Solution s;
		vector<int>ans;
		ans = s.grayCode(n);
		for (const auto& p : ans)
			cout << p << " ";
		cout << endl;
	}
	return 0;
}

大佬就找到了一种规则,左边乘2右边乘2+1,乘2补0,两连的两位同时补0,说明他们还是只有一位 不同,同时压入+1,那么压入的两位也是只有一位不同,因为是倒叙操作,最后一位就是0+1,那么最后一位和第一位也就实现了一位不同。

你可能感兴趣的:(每日一题,leetcode,c++,算法)