-5

我必须以这种方式组合一组值:

输入:

{A,B,C,D}

结果:

{AB, ABC, AC, AD, ACD, ABD, ABCD, BC, BD, BCD, CD}

我怎样才能做到这一点?

4

1 回答 1

0

根据输入的大小有几种解决方案:
如果输入数组 <= 64 并且输入不需要排序,我们可以将每个组合表示为 a long,其中每个位为 1,如果对应的元素在产生的输出中:

void generateCombination(int[] inp){
    long upper_bound = (1 << inp.length);

    for(long rep = 0 ; rep < upper_bound ; rep++){
        for(int i = 0 ; i < inp.length ; i++)
            if(rep & (1 << i) != 0)
                System.out.print(inp[i]);

        System.out.print(",");
    }
}

如果必须对输出进行排序,我们可以使用递归解决方案轻松解决此问题:

void generateCombinations(int[] inp , int[] combination , int at_i , int at_c){
    for(int i = at_i + 1 ; i < inp.length ; ++i)
    {
        combination[at_c] = inp[i];
        System.out.println(Arrays.toString(combination));

        generateCombinations(inp , combination , i , at_c + 1);
    }

    combination[at_c] = 0;
}

//this call will produce all combinations sorted ascending
generateCombinations(inpt , new int[inp.length] , -1 , 0);
于 2015-10-03T16:24:17.400 回答