binary reflected Gray code
二進制反射格雷碼
偽代碼描述
BRGC(n)
//遞歸生成n位的二進制反射格雷碼
//輸入:一個正整數n
//輸出:所有長度為n的格雷碼位串列表
if n=1,表L包含位串0和位串1
else 調用BRGC(n-1)生成長度為n-1的位串列表L1
把表L1倒序后復制給表L2
把0加到表L1中的每個位串前面
把1加到表L2中的每個位串前面
把表L2添加到表L1后面得到表L
return L;
難點
在我看來這里的難點主要是
1.位串和表的存儲結構
2.位串的動態添加
3.倒序復制操作
解決辦法
1.因為位串需要動態添加位數,并且需要在前方添加,因此使用list,表需要進行倒序復制,也可以使用list,但是為了避免混淆,這里使用vector
2.使用了list之后添加就很方便了
3.使用vector的反向迭代器進行倒序復制
#include <vector>
#include <list>
typedef vector<list<int>> VList;
VList BRGC(int n)
{
VList L;
if (n == 1)
{
list<int> zero,one;
zero.push_front(0);
one.push_front(1);
L.push_back(zero);
L.push_back(one);
}
else
{
VList L1;
L1 = BRGC(n - 1);
//使用list的接受迭代器范圍的構造函數初始化L2
VList L2(L1.rbegin(), L1.rend());
for(VList::iterator beg=L1.begin();beg!=L1.end();beg++)
{
(*beg).push_front(0);
}
for (VList::iterator beg = L2.begin(); beg != L2.end(); beg++)
{
(*beg).push_front(1);
}
L.insert(L.end(), L1.begin(), L1.end());
L.insert(L.end(),L2.begin(), L2.end());
}
return L;
}
int main()
{
int n;
cout << "please input the length of bit string :";
cin >> n;
VList L = BRGC(5);
int count = 0;
for each (list<int> var in L)
{
for each (int bit in var)
{
cout << bit;
}
cout << "\n";
count++;
}
cout <<"總位串數為:"<< count<<endl;
system("pause");
return 0;
}
總結
出現了一些小問題
1.錯用list的構造函數
BitString zero(0)
BitString one(1)
不能這樣用這個是用來分配存儲空間的,這里表示分配0個int型存儲空間,導致后面zero的容量為0,one的容量為1,并且其值被默認初始化為0
2.錯用for each(已修正)
for each里的參數都是拷貝復制過來的,導致位串的位數總是1,因為再foreach里添加位數之后那個臨時位串就被銷毀了,沒有對原位串造成任何改變