我正在尝试组合,但我不知道怎么做

tktrz96b  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(226)

在一个测试用例中,我有1234作为输入,我想得到
{1+2, 3+4}
{1+3, 2+4}
{1+4, 2+3}
但是我只能做{1+2,3+4}我想不出任何方法来获得{1+3,2+4}。我需要一些算法建议,想不出任何条件来做这个。

for (int j=0; j<woodLength.length; j++) {
        if (woodLength[j][2] != 1) {
            // a function that can create the boards using the wood pieces
            for (int i=0; i<woodLength.length; i++) {
                // set used boards as 1 and unused as 0
                if (woodLength[i][1] != 1) {
                    woodenBoardHeight.add(woodLength[i][0]+woodLength[i+1][0]);
                    System.out.println(woodenBoardHeight.get(wBHCount));
                    wBHCount ++;
                    woodLength[i][1] = 1;
                    woodLength[i+1][1] = 1;
                }
            }
            for (int i=0; i<woodLength.length; i++) {
                woodLength[i][1] = 0;
            }
            woodLength[j][2] = 1;
            woodLength[j+1][2] = 1;
        }
    }

这是我的代码,现在打印的是{3,7},但是我还需要{4,6}和{5,5}
如果有用的话,我想解决这个问题
https://www.cemc.uwaterloo.ca/contests/computing/2017/stage%201/senioref.pdf

ffdz8vbo

ffdz8vbo1#

一种创建数组所有组合的算法使用无符号二进制计数器。

Array:  1  2  3  4

        0  0  0  0     [] empty combination
        0  0  0  1     [4]
        0  0  1  0     [3]
        0  0  1  1     [3, 4]

等等。
在您的例子中,您需要2位加2位的组合。我们可以通过测试二进制计数器并在二进制计数器上正好有2位时创建组合来实现这一点。

Array:  1  2  3  4

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

在您的示例中,成对的顺序并不重要。你可以消除重复对,你有三个条件,你正在寻找。

dnph8jn4

dnph8jn42#

使用此代码可以按预期获得解决方案

public static void main(String[] args) {
    List<Integer> num;
    Integer[] numArray = {1,2,3,4};
    num = Arrays.asList (numArray);
    List<Integer> newList = new ArrayList<> ();

    for(int i=1;i<num.size ();i++) {
        int[] intArray = new int[2];
        newList.addAll (num);
        newList.remove (0);
        newList.remove (i-1);
        intArray[0]=num.get (0)+num.get (i);
        intArray[1] = newList.get (0)+newList.get (1);
        System.out.println ("{"+intArray[0]+","+intArray[1]+"}");

    }
}

结果如下:

{3,7}
{4,6}
{5,5}

相关问题