在集合0-N中查找基数C的所有可能子集

时间:2017-04-17 21:43:26

标签: c++ set

你怎么能得到一组N大小并打印给定基数的所有可能子集?

  

e.g。 [0 1 2],2 - > [0 1],[0 2],[1,2]

我找不到代码,我花了一些时间写,所以我觉得它可能会有所帮助:)

1 个答案:

答案 0 :(得分:1)

您可以使用此功能:

void printSets(int N, int Cardinality)
{
        std::vector<int> nums;
        helper(nums, 0, 0, N, Cardinality);    
}

使用辅助功能:

void helper(std::vector<int> &nums, int size, int index, int max, int cardinality)
{
        if (size == cardinality) //SET IS READY TO PRINT (base case)                                   
        {
            for (int k = 0; k < cardinality; ++k)
                    std::cout<< nums[k] << " ";
            std::cout << std::endl;
            return;
        }
        for (int i = index; i < max+1; ++i)   //WE LOOP THROUGH THE SPACES LEFT            
        {
            nums.push_back(i);
            helper(nums, size+1, i+1, max, cardinality);  //WE NEST AS MANY LOOPS AS THE CARDINALITY
            nums.pop_back();
        }
}