按词典顺序生成k组合 [英] Generating k-combinations lexicographically

查看:120
本文介绍了按词典顺序生成k组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道,也找不到算法来按字典顺序生成k个项(即k个子集)的组合.我确实知道生成n个选择k的组合的算法,但是它们不按字典顺序生成k个子集.

I'm not aware nor could I find an algorithm to generate combinations of k items (i.e. k-subsets) lexicographically. I do know algorithms to generate combinations of n choose k, but they don't generate the k-subsets lexicographically.

有人可以帮我解决这个问题或为我指明正确的方向吗?

Can somebody help me out with this or point me in the right direction?

推荐答案

以下算法将生成集合元素的所有组合:

The following algorithm will generate all combinations of elements of a set:

procedure all_combinations(S)

    if length(S) == 0
        return {}
    else
        all_comb = {}
        x = first element of S
        Sx = S-{x}
        for each C in all_combinations(Sx)
            all_comb += C
            all_comb += {x} ∪ C
        return all_comb

对于集合{1,2,3},此算法可以…

For the set {1,2,3}, this algorithm does…

all_combinations({2,3})

all_combinations({2,3})

all_combinations({3})

all_combinations({3})

all_combinations({}),返回{}

all_combinations({}), which returns {}

all_combinations({3})返回{{},{3}}

all_combinations({3}) returns {{}, {3}}

all_combinations({2,3})返回{{},{2},{3},{2,3}}

all_combinations({2,3}) returns {{}, {2}, {3}, {2,3}}

all_combinations({1,2,3})返回{{},{1},{2},{1,2},{3},{1,3},{2,3},{1 ,2,3}}

all_combinations({1,2,3}) returns {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}}

这篇关于按词典顺序生成k组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆