0
My Output   : [0,1,3,2,6,7,5,4,13,12,14,15,10,11,9,8]
Expected O/P: [0,1,3,2,6,7,5,4,13,12,14,15,10,11,9,8]
n = 4

在调试时它正在做正确的索引计算,但它仍然首先添加 13 而不是 12。

问题:n 位格雷码序列是 2n 个整数的序列,其中:

每个整数都在 [0, 2n - 1] 范围内,第一个整数是 0,一个整数在序列中出现的次数不超过一次,每对相邻整数的二进制表示正好相差一位,并且二进制第一个和最后一个整数的表示正好相差一位。给定一个整数 n,返回任何有效的 n 位格雷码序列。

我的解决方案:

public static List<Integer> grayCode(int n) {
            List<Integer> resuList = new ArrayList<Integer>();
            resuList = callrecursion(n);
            return resuList;
            
        }
    
        public static List<Integer> callrecursion(int n){
    
            if (n==1) {
                List<Integer> list = new ArrayList<Integer>();
                list.add(0);
                list.add(1);
                return list;
            }
    
            List<Integer>result = new ArrayList<>();
    
            List<Integer> list = callrecursion(n-1);
    
            for (Integer integer : list) {
    
                result.add(integer);
            }
            for (int i = list.size(); i >0; i--) {
                int x = (int)Math.pow(2, n-1);
                int sun = x+result.indexOf(i-1);
                result.add(sun);
            }
    
    
            return result;
    
        }
4

1 回答 1

1

indexOf没有按照您的想法行事(在文档中查找)。改用这个

int sun = x+result.get(i-1);

这导致结果

[0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8]

这是一个格雷码。

于 2021-11-01T06:56:59.077 回答