sotanishy's competitive programming library

sotanishy's code snippets for competitive programming

View the Project on GitHub sotanishy/cp-library-cpp

:warning: Enumerate Subsets
(misc/enumerate_subsets.hpp)

Code

#pragma once
#include <vector>

/**
 * @brief Enumerate Subsets
 */
std::vector<int> enumerate_subsets(int n, int k) {
    if (k < 0 || n < k) return {};
    if (k == 0) return {0};
    std::vector<int> ret;
    int comb = (1 << k) - 1;
    while (comb < (1 << n)) {
        ret.push_back(comb);
        int x = comb & -comb;
        int y = comb + x;
        comb = ((comb & ~y) / x >> 1) | y;
    }
    return ret;
}
#line 2 "misc/enumerate_subsets.hpp"
#include <vector>

/**
 * @brief Enumerate Subsets
 */
std::vector<int> enumerate_subsets(int n, int k) {
    if (k < 0 || n < k) return {};
    if (k == 0) return {0};
    std::vector<int> ret;
    int comb = (1 << k) - 1;
    while (comb < (1 << n)) {
        ret.push_back(comb);
        int x = comb & -comb;
        int y = comb + x;
        comb = ((comb & ~y) / x >> 1) | y;
    }
    return ret;
}
Back to top page