利用性质:已知n-1位格雷码的情况下,对其进行镜像操作,并在最高位填上1,就可以n位格雷码。

递归实现

  1. import java.util.LinkedList;
  2. import java.util.List;
  3. public class GreyCode {
  4. public static List<Integer> greyCode(int n) {
  5. if (n == 1) {
  6. List<Integer> ans = new LinkedList<>();
  7. ans.add(0);
  8. ans.add(1);
  9. return ans;
  10. }
  11. List<Integer> ans = greyCode(n - 1);
  12. for (int num = 1 << (n - 1), i = ans.size() - 1; i >= 0; --i) {
  13. ans.add(ans.get(i) + num);
  14. }
  15. return ans;
  16. }
  17. public static void main(String[] args) {
  18. System.out.println(greyCode(3));
  19. }
  20. }

非递归

用循环实现,不需要递归,使用ArrayList在get的时候可以由更高的效率。

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class GreyCode {
  4. public static List<Integer> greyCode(int n) {
  5. List<Integer> ans = new ArrayList<>(1 << n);
  6. ans.add(0);
  7. for (int i = 0, plus = 1; i < n; ++i, plus = 1 << i) {
  8. for (int j = ans.size() - 1; j >= 0; --j) {
  9. ans.add(ans.get(j) + plus);
  10. }
  11. }
  12. return ans;
  13. }
  14. public static void main(String[] args) {
  15. System.out.println(greyCode(3));
  16. }
  17. }

异或编码

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class GreyCode {
  4. public static List<Integer> greyCode(int n) {
  5. List<Integer> ans = new ArrayList<>(1 << n);
  6. for (int i = 0; i < 1 << n; ++i) {
  7. ans.add(i ^ (i >> 1));
  8. }
  9. return ans;
  10. }
  11. public static void main(String[] args) {
  12. System.out.println(greyCode(3));
  13. }
  14. }