日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Gray Code

發布時間:2024/10/12 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

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 a valid gray code sequence according to the above definition.

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

就是把n位二進制數都轉成十進制返回。代碼:

1 vector<int> grayCode(int n) { 2 vector<int> result; 3 if(!n) { 4 result.push_back(0); 5 return result; 6 } 7 bool* bits = (bool*)malloc(n); 8 memset(bits,0,n); 9 getGrayCode(result,n,0,bits); 10 return result; 11 } 12 void getGrayCode(vector<int>& result,int n,int i,bool* bits){ 13 if(n==i){ 14 result.push_back(b2i(bits,n)); 15 return ; 16 } 17 getGrayCode(result,n,i+1,bits); 18 bits[i]=!bits[i]; 19 getGrayCode(result,n,i+1,bits); 20 } 21 int b2i(bool* bits,int n){ 22 int result=0,c=0; 23 for(int i=n-1;i>=0;i--){ 24 if(!c) c=1; 25 else c*=2; 26 if(bits[i]){ 27 result += c; 28 } 29 } 30 return result; 31 }

時間復雜度太大了,以為過不了,結果還是過了,都2n*n了。不過規模已經是指數級,沒辦法降啊。
后來看到這個解法,于是去wikipedia上面看了下,確實非常簡單,下面的鏈接:
http://blog.csdn.net/doc_sgl/article/details/12251523

?

?

轉載于:https://www.cnblogs.com/mike442144/p/3475451.html

總結

以上是生活随笔為你收集整理的Gray Code的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。