开发者

iterative algorithm for combination generation [duplicate]

This question already has answers here: Closed 12 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜