如何使用 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;
}
posted @ 2018-05-03 17:36  學海無涯  阅读(787)  评论(0编辑  收藏  举报