iterative algorithm for combination generation [duplicate]
Possible Duplicate:
Algorithm to return all combinations of k elements from n
Is there any iterative algorithm to generate combinations of N numbers taking 'r' at a tim开发者_运维知识库e ?
Yes there is.
Here is code from the wrong answer Library.
void generate_combos(int n, int k) {
int com[100];
for (int i = 0; i < k; i++) com[i] = i;
while (com[k - 1] < n) {
for (int i = 0; i < k; i++)
cout << com[i] << " ";
cout << endl;
int t = k - 1;
while (t != 0 && com[t] == n - k + t) t--;
com[t]++;
for (int i = t + 1; i < k; i++) com[i] = com[i - 1] + 1;
}
}
This generates the combinations in lexicographic order.
精彩评论