Iterative algorithm for generating combinations

Possible duplicate:
Algorithm for returning all combinations of elements k from n

Is there an iterative algorithm for generating combinations of N numbers taking "r" at a time?

+4
source share
1 answer

Yes there is.

Here is the 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 creates combinations in lexicographical order.

+9
source

Source: https://habr.com/ru/post/1337681/


All Articles