C++中排列、组合和PowerSet的实现

use*_*106 -4 c++ combinations permutation powerset c++11

我正在寻找使用 C+++ 的 Permutation、Combination 和 PowerSet 的实现

Jar*_*d42 5

使用 STL:

排列

使用 std::next_permutation

template <typename T>
void Permutation(std::vector<T> v)
{
    std::sort(v.begin(), v.end());
    do {
        std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
        std::cout << std::endl;
    } while (std::next_permutation(v.begin(), v.end()));
}
Run Code Online (Sandbox Code Playgroud)

组合:

template <typename T>
void Combination(const std::vector<T>& v, std::size_t count)
{
    assert(count <= v.size());
    std::vector<bool> bitset(v.size() - count, 0);
    bitset.resize(v.size(), 1);

    do {
        for (std::size_t i = 0; i != v.size(); ++i) {
            if (bitset[i]) {
                std::cout << v[i] << " ";
            }
        }
        std::cout << std::endl;
    } while (std::next_permutation(bitset.begin(), bitset.end()));
}
Run Code Online (Sandbox Code Playgroud)

电源组:

请注意,如果大小小于整数的位数,则可以使用该整数而不是vector<bool>. 如果大小是在编译时已知,喜欢std::bitset<N>std::vector<bool>

bool increase(std::vector<bool>& bs)
{
    for (std::size_t i = 0; i != bs.size(); ++i) {
        bs[i] = !bs[i];
        if (bs[i] == true) {
            return true;
        }
    }
    return false; // overflow
}

template <typename T>
void PowerSet(const std::vector<T>& v)
{
    std::vector<bool> bitset(v.size());

    do {
        for (std::size_t i = 0; i != v.size(); ++i) {
            if (bitset[i]) {
                std::cout << v[i] << " ";
            }
        }
        std::cout << std::endl;
    } while (increase(bitset));
}
Run Code Online (Sandbox Code Playgroud)

活生生的例子