【LeetCode】89. 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 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:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
             A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = 1.
             Therefore, for n = 0 the gray code sequence is [0].

 

描述:

给出一个n表示二进制的位数,请求输出位数不高于该位数的所有数,其中要求每两个相邻数只有一位不同

 

分析:

刚开始一位只需要相邻的两个数的1的个数差1,然后发现不对....

确实没想到思路,看了大神的博客(博客地址),

但是其实还是没太明白,后面有机会再研究一下...

 

代码:(错误代码,按照相邻两个数差1做的)

class Solution {
public:
	vector<int> grayCode(int n) {
		vector<vector<int>> number;
		for(int i = 0; i <= n; ++ i) {
			vector<int> temp;
			number.push_back(temp);
		}
		
		int max_number = 1 << n;
		for(int i = 0; i < max_number; ++ i) {
			int count = count_number(i);
			number[count].push_back(i);
            // cout << i << "  " << count << endl;
		}
		// cout << endl;
        
		vector<int> result;
		
		int index = 0, cnt = max_number;
		while (cnt) {
			while (index < n && number[index].size()) {
				// cout << index << cnt << endl;
				result.push_back(number[index][0]);
				number[index].erase(number[index].begin());
				++ index;
				--cnt;
				
			}
			index -= 2;
			while (index >= 0 && number[index].size()) {
				// cout << index << cnt << endl;
				result.push_back(number[index][0]);
				number[index].erase(number[index].begin());
				-- index;
				-- cnt;
			}
			index += 2;
		}
		
		return result;
	}
	
	int count_number(int i) {
		int result = 0;
		while (i) {
			if (i & 1) {
				++ result;
			}
			i >>= 1;
		}
		return result;
	}
};

 

代码二:

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

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页