利用性质:已知n-1位格雷码的情况下,对其进行镜像操作,并在最高位填上1,就可以n位格雷码。
递归实现
import java.util.LinkedList;
import java.util.List;
public class GreyCode {
public static List<Integer> greyCode(int n) {
if (n == 1) {
List<Integer> ans = new LinkedList<>();
ans.add(0);
ans.add(1);
return ans;
}
List<Integer> ans = greyCode(n - 1);
for (int num = 1 << (n - 1), i = ans.size() - 1; i >= 0; --i) {
ans.add(ans.get(i) + num);
}
return ans;
}
public static void main(String[] args) {
System.out.println(greyCode(3));
}
}
非递归
用循环实现,不需要递归,使用ArrayList在get的时候可以由更高的效率。
import java.util.ArrayList;
import java.util.List;
public class GreyCode {
public static List<Integer> greyCode(int n) {
List<Integer> ans = new ArrayList<>(1 << n);
ans.add(0);
for (int i = 0, plus = 1; i < n; ++i, plus = 1 << i) {
for (int j = ans.size() - 1; j >= 0; --j) {
ans.add(ans.get(j) + plus);
}
}
return ans;
}
public static void main(String[] args) {
System.out.println(greyCode(3));
}
}
异或编码
import java.util.ArrayList;
import java.util.List;
public class GreyCode {
public static List<Integer> greyCode(int n) {
List<Integer> ans = new ArrayList<>(1 << n);
for (int i = 0; i < 1 << n; ++i) {
ans.add(i ^ (i >> 1));
}
return ans;
}
public static void main(String[] args) {
System.out.println(greyCode(3));
}
}