我想获得一个数组的所有组合使用C ++这样
I am trying to get all combinations of an array with C++ such that
double* list1 = new double[size];
在该数组的项目是 {1,2,3,4,5}
我需要添加所有可能的组合成一个堆栈,如:
I need to add all possible combinations into a stack, such as:
1+2, 1+2+3, 1+2+3+4,1+2+3+4+5, 1+3, 1+3+4, 1+3+4+5, 1+4, 1+4+5, 1+5...
我遇到的我做这通过2 for循环的问题,while循环
the problem I am running into is I am doing this through 2 for loops and a while loop
for(int i = 0; i < size - 1; i++)
{
for(int j = i; j < size - 1; j++)
{
double temp = list1[i] + list1[j + 1];
list1combos.push(temp);
int k = j + 2;
while (k <= size - 1)
{
temp = temp + list1[k];
list1combos.push(temp);
k++;
}
}
}
我可以得到那些我上面列出的,但我不知道如何code的组合,如 1 + 3 + 5
或 1 + 2 + 5
请就如何得到这些的组合,谢谢计算器!
Please advise on how to get those combinations, thanks stackoverflow!
由于顺序并不重要,我建议具有相同大小的数组作为你的 X
并在其上执行二进制增量,即你开始与inited仅 0
和数组数,直到你只有 1
秒。对于每一个另外的 1
你会选择置换从 X
阵列。
Since the order does not matter, I would suggest having an array of the same size as your x
and perform a binary increment on it, i.e. you start with the array inited to only 0
s and count until you have only 1
s. For every addition of a 1
you would pick a permutation from your x
array.
First iteration:
0 0 0 0 0 -> empty
Second iteration:
0 0 0 0 1 -> you pick 5
3rd iteration:
0 0 0 1 0 -> you pick 4
4th iteration:
0 0 0 1 1 -> you pick 4 and 5
And so on until you reach:
1 1 1 1 1 -> you pick 1, 2, 3, 4 and 5