有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的动态移动数组

例如,我有一个连续开始的k元素数组 01 2

我试着让它向上移动到一个特定的值,比如4,以

  • 01 2
  • 01 3
  • 01 4
  • 023
  • 024
  • 034

我知道,每当数组中的最后一个元素达到最大值时,它都必须增加上一个索引,并将当前索引设置为上一个索引的值+1,如果上一个索引的值比最大值少1,我们将重复上一个索引的步骤,依此类推

但我不确定如何处理它,使其适用于任何k元素数组

非常感谢您的任何提示或建议

更新:我尝试创建一个递归移动索引并尝试添加的方法。它是有效的,但我不认为它非常有效:/

public static int[] nextCombi(int[] arr, int index, int maxVal){
    if (index < 0 || maxVal < 0){
        return arr;
    }
    else{
        if (arr[index] + 1 == maxVal){
            if (index - 1 >= 0){
                nextCombi(arr, index - 1, maxVal - 1);
                arr[index] = arr[index - 1] + 1;
            }
            else{
                arr[index]++;
                return arr;
            }
        }

        else{
            // Can add
            arr[index]++;
        }
    }
    return arr;
}

大体上

while (true){
    arr = nextCombi(arr, max, n);
    if (arr[0] > max)
        break;
}

共 (1) 个答案

  1. # 1 楼答案

    我认为你应该从列表的末尾开始,升级到没有达到最大值,然后开始列表中的第一项

    下面是一个例子:

    List<Integer> ints = new ArrayList<>(); // create the list
    ints.addAll(Arrays.asList(0, 1, 3)); // add element in it:
    int max = 4; // indicate max value
    int maxOfLast = Integer.MAX_VALUE; // start with max value to be sure of not reached max
    for(int currentIndex = ints.size() - 1; currentIndex >= 0; currentIndex ) {
        int current = 0;
        while((current = ints.get(currentIndex)) < max && (current + 1) < maxOfLast) { // until it's not the end or reach max of index + 1 value
            ints.set(currentIndex, ++current); // upgrade it
            System.out.println(ints); // print (see output)
        }
        maxOfLast = ints.get(currentIndex); // set current value as max for next interation
    }
    

    输出:

    [0, 1, 4]
    [0, 2, 4]
    [0, 3, 4]
    [1, 3, 4]
    [2, 3, 4]