在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
测试样例:
1
返回:["0","1"]
};
}
今天才弄懂什么是格雷码,题目给的n代表位数而不是一个整数,格雷码的n个位数意味着有2的n次方个二进制数,每个二进制数为n位,每个二进制数相比,都只有一位二进制码不相同;比如n=1,{0,1};n=2,{00,01,11,10};n=3,{000,001,011,010,110,111,101,100} void gray(vector<string>& v,int bit,int n) { if(bit==n) return; vector<string> temp; for(int i=0;i<v.size();i++) temp.push_back("0"+v[i]); for(int i=v.size()-1;i>=0;i--) temp.push_back("1"+v[i]); v.swap(temp); gray(v,bit+1,n); } vector<string> getGray(int n) { // write code here vector<string> v; v.push_back("0"); v.push_back("1"); if(n==1) return v; gray(v,1,n); return v; }
# -*- coding:utf-8-*-from sys importexitclassGrayCode:def getGray(self, n):# write code heredef _getGray(x):count=2**xans=[]ifx<1:exit(-1)elif x==1:ans.append("0")ans.append("1")returnanselse:temp=_getGray(x-1)j=len(temp)fori in range(j):ans.append("0"+temp[i])whilej>0:ans.append("1"+temp[j-1])j-=1returnansreturn_getGray(n)
using System.Collections.Generic; class GrayCode { publicstring[] getGray(int n) { string[] Gray = {"0", "1"}; if(n == 1) return Gray; string[] LastRank = getGray(n - 1); List<string> ThisRank = new List<string>(); for(int Index = 0; Index < LastRank.Length; Index++) ThisRank.Add("0"+ LastRank[Index]); for(int Index = LastRank.Length - 1; Index >= 0; Index--) ThisRank.Add("1"+ LastRank[Index]); return ThisRank.ToArray(); } }
import java.util.*; public class GrayCode { public String[] getGray(int n) { // write code here return (String[])helper(n).toArray(new String[n]); } private ArrayList<String> helper(int n) { ArrayList<String> gray = new ArrayList<>(); if(n == 1){ gray.add("0"); gray.add("1"); return gray; } ArrayList<String> last_gray = helper(n - 1); // 在首位添加"0" for(int i = 0; i < last_gray.size(); i++) gray.add("0" + last_gray.get(i)); // 在首位添加"1" for(int i = last_gray.size() - 1; i >= 0; i--) gray.add("1" + last_gray.get(i)); return gray; } }
public class gerryCode { // 1 : 0 1 //2 : 00 01 11 10 //3 :["000","001","011","010","110","111","101","100"] public String[] getGray(int n) { Queue<StringBuilder> queue = new LinkedList<>(); getGray(n,queue); String[] res = new String[queue.size()]; int i = 0; while ( !queue.isEmpty()){ res[i] = queue.poll().toString(); i++; } return res; } public void getGray(int n, Queue<StringBuilder> queue){ // Base if( n == 1){ queue.add(new StringBuilder().append(0)); queue.add(new StringBuilder().append(1)); return; } getGray(n-1,queue); int size = queue.size(); while (size > 0){ int i; i = size & (byte)1; StringBuilder poll = queue.poll(); StringBuilder nextSb = new StringBuilder(poll); poll.append(i); nextSb.append(1-i); queue.offer(poll); queue.offer(nextSb); size --; } } public static void main(String[] args) { gerryCode gerryCode = new gerryCode(); System.out.println(Arrays.toString(gerryCode.getGray(3))); } }
参考大神的公式
package com.special.improve;
import java.util.Arrays;
import java.util.Scanner;
/**
* 腾讯01-格雷码
*
* 公式: G(n) = n XOR (n / 2)
* 还有就是公式得到是十进制形式,要转换成二进制
*
* Create by Special on 2018/3/5 19:05
*/
public class Pro043Improve1 {
/**
* 十进制转二进制,且包括前导向性0
* @param num
* @param n
* @return
*/
public static String convertToString(int num, int n){
char[] results = new char[n];
Arrays.fill(results, '0');
int index = n;
while(num != 0){
results[--index] = (num & 1) == 0 ? '0' : '1';
num >>>= 1;
}
return new String(results);
}
public static String[] getGray(int n) {
int numbers = (int) Math.pow(2, n);
String[] result = new String[numbers];
for(int i = 0; i < numbers; i++){
result[i] = convertToString(i ^ (i >> 1), n);
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int n = input.nextInt();
String[] results = getGray(n);
for(int i = 0; i < results.length; i++){
System.out.print(results[i] + " ");
}
System.out.println();
}
}
}
class GrayCode { public: vector<string> getGray(int n) { vector<string> g; if(n==1){ g.push_back("0"); g.push_back("1"); return g; } vector<string> s = getGray(n-1); for(int i=0;i<s.size();i++) g.push_back("0"+s[i]); for(int i=s.size()-1;i>=0;i--) g.push_back("1"+s[i]); return g; } };
class GrayCode { public: vector<string> grr; void GR( vector<string> gr ,int n){ grr.clear(); string a ="0"; string b ="1"; string temp; for(int i=0;i<gr.size();i++){ grr.push_back(gr[i] + a); grr.push_back(gr[i] + b); temp = a; a = b; b = temp; } if( grr.size() < pow(2,n) ) GR(grr,n); } vector<string> getGray(int n) { vector<string> gr; gr.push_back("0"); gr.push_back("1"); if(n>1){ GR(gr,n); return grr; } else return gr; } };
//标准递归,通俗易懂
class GrayCode {
public:
vector<string> result;
int length;
vector<string> getGray(int n) {
string gray = "";
for(int i=0;i<n;i++)
gray += '0';
length = n;
gray[0] = '0';
generateGray(gray, 1, 0);
gray[0] = '1';
generateGray(gray, 1, 1);
return result;
}
void generateGray(string &gray, int l, int x)
{
if(l==length)
{
result.push_back(gray);
return;
}
else
{
if(x==0)
{
gray[l] = '0';
generateGray(gray, l+1, 0);
gray[l] = '1';
generateGray(gray, l+1, 1);
}
else
{
gray[l] = '1';
generateGray(gray, l+1, 0);
gray[l] = '0';
generateGray(gray, l+1, 1);
}
}
}
};
class GrayCode { public: vector<string> getGray(int n) { string ini(n); return gray(ini,n); } vector<string> gray(string ini,int num){ vector<string> s; if(num==1){ s.push_back(ini); ini[ini.size()-1]='1'; s.push_back(ini); return s; } s=gray(ini,num-1); auto tem=s; int m=s.size(); auto i=tem.end(); while(m--){ --i; (*i)[(*i).size()-num]='1'; s.push_back(*i); } return s; } };
public String[] getGray(int n) { if(n == 1) { return new String[]{"0", "1"}; } String[] temp = getGray(n - 1); String[] strings = new String[temp.length * 2]; for(int i = 0,j = temp.length; i < temp.length *2; i++) { if(i < temp.length) { strings[i] = "0" + temp[i]; } else { j--; strings[i] = "1" + temp[j]; } } return strings; }
classGrayCode {public:vector<string> getGray(intn) {// write code hereif( n == 1){returnvector<string>{"0","1"};}vector<string> && s = getGray( n - 1);vector<string> result;result.reserve( s.size() * 2);for( inti = 0; i < s.size(); ++i )result.push_back("0"+s[i]);for( inti = s.size() - 1; i >=0; --i )result.push_back("1"+s[i]);returnresult;}};
//格雷码递归实现 public class GrayCode { public String[] getGray(int n) { // write code here int m=1<<n; String[]str=new String[m]; if(n==1){ str[0]="0"; str[1]="1"; return str; } String[]tem=getGray(n-1); int j=0; for(int i=0;i<m;i++){ if(i<m/2){//前半部分前边添加“0” str[i]="0"+tem[j++]; }else{//后半部分添加“1”,并倒序 str[i]="1"+tem[--j]; } } return str; } }
class GrayCode { public: vector<string> getGray(int n) { // write code here vector<string> vc; vc.push_back("0"); vc.push_back("1"); int cc=1; while(cc<n) { vector<string> vc_new; for(int i =0;i<vc.size();i++) vc_new.push_back("0"+vc[i]); for(int i=vc.size()-1;i>=0;i--) vc_new.push_back("1"+vc[i]); vc = vc_new; cc++; } return vc; } };