问题
I am trying to generate every possible unique combination from an array, but its not as straightforward as generating all combinations..... Eg. I have an array {a,b,c,d,e,f} ... my result should be like this...
- ab, cd, ef
- abc, def
- ac, bd, ef
- abcf, ed
- ....etc
...... basically in every result set all elements of the array should be included .... Also 'ab' is the same as'ba' and 'abcd' is the same as 'dcba' or 'cbda' .... The position does not matter .... and no repetition allowed ... 'aaa' or 'aa' is not valid ... would be grateful if someone could provide a solution for this problem ....
回答1:
I suggest that you build all possible unique sets of set sizes. Then insert all possible values in all possible orders. For example, with 5 possible values, you have the set sizes:
1 1 1 1 1
1 1 1 2
1 2 2
1 1 3
1 4
2 3
5
Now, put the actual values in to the sets. For the first set of set sizes, we get:
a, b, c, d, e
That isn't very interesting because all the sets are the same size, so skip to the third set of set sizes. Here, we fill the sets and then shift them, giving us:
a, bc, de
b, cd, ea
c, de, ab
d, ea, bc
e, ab, cd
This isn't a full solution, but I've split the problem in two and I think you can take it from there.
回答2:
String [] new_array=new String[N];
array.length=length.of("befdac");
for(int i=0;i < array.length;i++) //this is first digit
{
for(int j=0;j < array.length;j++) //this is second digit
{
if(i==j)continue;
................ same with other digits
{
if((i==j)||(i==k)) continue;
// start counting in this most inner block
new_array[i][j][k][l]...[last_digit]=byte(i+65)+byte(j+65)+byte(k+65)+.....+byte(last_digit+65);
//65=a, 66=b,......
}
}
}
new_array[][][][]...[] will be your code i didnt tried . best thing u do it yourself. this is not optimized. just made for first answer to get some points
来源:https://stackoverflow.com/questions/11162226/generating-unique-combinations-from-an-array-but-having-every-element-in-each-co