1. 程式人生 > >【LeetCode】89. Gray Code(C++)

【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;
	}
};