码迷,mamicode.com
首页 > 其他好文 > 详细

89.Gray Code(回溯)

时间:2015-02-11 09:24:25      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

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

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

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0

01 - 1

11 - 3

10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also avalid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray codesequence. Sorry about that.

HideTags

 Backtracking



#pragma once
#include<iostream>
#include<vector>
using namespace std;

//数组A转int
int parseint(int *A, int n)
{
	int result = 0;
	for (int i = 0; i < n; i++)
		result += (int)pow(2, i)*A[i];
	return result;
}

vector<int> grayCode(int n) 
{
	vector<int> result;
	result.push_back(0);//初始值0
	if (n == 0)
		return result;
	int rangesize = (int)pow(2, n);
	int *range = new int[rangesize];//对rangesize个数是否打印的标志位
	for (int i = 0; i < rangesize; i++)
		range[i] = 0;//未打印
	int *flag = new int[n];
	for (int i = 0; i < n; i++)
		flag[i] = 0;//初始化flag数组
	range[0] = 1;//0处设置为已打印。
	while (true)//最后的序列可能不包含rangesize内的所有整数?经测试,貌似是包含所有的
	{
		for (int i = 0; i < n; i++)
		{
			flag[i] = 1 - flag[i];
			int temp = parseint(flag,n);
			if (range[temp]==0)//未输出
			{
				result.push_back(temp);
				range[temp] = 1;//设置为已输出
				break;//跳出内层循环
			}
			else
			{
				flag[i] = 1 - flag[i];//归位
				if (i==n-1)
					return result;//每找到,返回.....................出口
				continue;//继续下一次
			}
		}
	}
}

void main()
{
	int a[] = { 1, 1, 1, 1 };
	cout << parseint(a, 4) << endl;
	vector<int> result = grayCode(11);
	for (int i = 0; i < result.size(); i++)
		cout << result[i] << ' ';
	cout << endl;
	cout << "result.size=" << result.size() << endl;//经测试,所有可能是能够全部输出的
	system("pause");
}




89.Gray Code(回溯)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43707405

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!