all combinations of k elements out of n

后端 未结 5 2144
星月不相逢
星月不相逢 2020-12-01 03:23

Can somebody provide me a link or pseudocode of a function for finding all combinations of k elements out of n? possibly in STL. I don\'t need to compute n choose k, I need

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 03:37

    You could use std::next_permutation but it is n! and not n choose k. You could filter them after you created them. But this solution is O(n!), not really perfect. Here is the trial and error solution:

    int factorial(int value)
    {
        int result = 1;
    
        for(int i = 1; i <= value; i++)
        {
            result *= i;
        }
    
        return result;
    }
    
    std::set> binomial_coefficient(std::vector input, int k)
    {
        std::set> solutions;
    
        for(unsigned int i = 0; i < factorial(input.size()); i++)
        {
            std::next_permutation(input.begin(), input.end());
    
            solutions.insert(std::set(input.begin(), input.begin() + k));
        }
    
        return solutions;
    }
    

提交回复
热议问题