如何使用 stl 进行排列组合?
Posted 學海無涯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用 stl 进行排列组合?相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <vector>
#include <algorithm>
//从 indexs 集合中选择 num 个元素进行组合并保证返回的组合中没有重复的元素
std::vector<std::vector<int>> combination(const int num,std::vector<int> &indexs)
{
std::vector<std::vector<int>> set;
if (num > indexs.size())return set;
std::vector<int> elements;
elements.resize(indexs.size());
for (int i = 0; i < num; i++)
{
elements.at(i) = 1;
}
do
{
std::vector<int> currentCombination;
for (size_t i = 0; i < elements.size(); ++i)
{
if (elements[i])
{
currentCombination.push_back(indexs[i]);
}
}
set.push_back(currentCombination);
} while (prev_permutation(elements.begin(), elements.end()));
//std::cout << set.size() << std::endl;
return set;
}
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<int>>& data)
{
for (int i = 0;i < data.size();i++)
{
os << i << ": ";
for (int j = 0;j < data[i].size();j++)
{
os << data[i][j] << ",";
}
os << "\n";
}
return os;
}
inline unsigned int factorial(unsigned int value)
{
unsigned int local_value = value;
while (value-- > 1)
{
local_value *= value;
}
return local_value;
}
unsigned int combination(unsigned int k,unsigned int n)
{
if (k > n)
{
return 0;
}
return factorial(n)/ (factorial(k)*factorial(n - k));
}
int main()
{
std::vector<int> indexs = { 1,2,3,4,5,6,7,8,9 };
const int num = 4;
std::cout << combination(num, indexs) << std::endl;
getchar();
return 0;
}
以上是关于如何使用 stl 进行排列组合?的主要内容,如果未能解决你的问题,请参考以下文章