【LeetCode】89. Gray Code(C++)

地址:https://leetcode.com/problems/gray-code/

题目:

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Example 1:
在这里插入图片描述

Example 2:
在这里插入图片描述

理解:

有点像permutation,想到用backtracking求解,但是具体实现还是有些不太一样吧,下面是我的实现,但是并不能跑出来正确的结果。

实现:

class Solution {
public:
	vector<int> grayCode(int n) {
		vector<string> res;
		string tmp(n, '0');
		dfs(res, tmp, 0, n);
		vector<int> intRes(pow(2,n),0);
		for (int i = 0; i < res.size(); ++i)
			intRes[i] = trans(res[i]);
		return intRes;
	}

private:
	void dfs(vector<string>& res, string& tmp, int beg, int n) {
		if (beg == n) {
			res.push_back(tmp);
			return;
		}
		for (int i = beg; i < n; ++i) {
			dfs(res, tmp, i + 1, n);
			tmp[i] = '1';
		}
	}

	int trans(const string& str) {
		int res = 0;
		for (int i = 0; i < str.length(); ++i) {
			res *= 2;
			res += str[i] == 0 ? 0 : 1;
		}
		return res;
	}
};

这样应该是不行的,改成1以后就改不回来了,不能满足gray码的特点。是不是可以多用一个数组去记录是第几次访问?但是好像也不太好实现。参考下别人的方法,其中flip这个操作,会先把0变成1,当第二次再调用的时候会把1再变回0。

class Solution {
public:
	vector<int> grayCode(int n) {
		bitset<32> bits;
		vector<int> res;
		backtracking(bits, res, n);
		return res;
	}

private:
	void backtracking(bitset<32>& bits, vector<int>& res, int k) {
		if (k == 0) {
			res.push_back(bits.to_ulong());
			return;
		}
		backtracking(bits, res, k - 1);
		bits.flip(k - 1);
		backtracking(bits, res, k - 1);
	}
};

实现2:

还可以用非递归的方法,利用gray码的特点,长为n的格雷码,就是长为n-1的前面加0和长为n-1的逆序排列,在前面加1。

class Solution {
public:
	vector<int> grayCode(int n) {
		vector<int> res(1, 0);
		for (int i = 0; i < n; ++i) {
			int preCnt = res.size();
			int tmp = (1 << i);
			while (preCnt) {
				res.push_back(tmp + res[preCnt - 1]);
				--preCnt;
			}
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84935920