1 求集合中元素的全排列(递归)
原理:从集合中选出一个元素作为排列的第一个元素,然后对剩余的元素进行全排列。如此递归处理,从而得到所有元素的全排列。
以对 123 进行全排列为例.
可以按以下步骤执行:
将1固定在第一位,求剩余23的排列,得到 123 132
将2固定在第一位,求剩余13的排列,得到:213 231
将3固定在第一位,求剩余12的排列,得到:312 321
#ifndef ObjectPermutationAndCombination_hpp_
#define ObjectPermutationAndCombination_hpp_
#include <list>
#include <vector>
#include <algorithm>
using std::vector;
using std::list;
template<class _InputIter, class _Tp>
class ObjectPermutation
{
public:
ObjectPermutation(_InputIter first, _InputIter last, std::list< std::vector<_Tp> > &output) :
_first(first), _last(last), _output(output){
}
void calcPermutationWithRecursion() {
_calcPermutationWithRecursion(_first, _last);
}
private:
void _calcPermutationWithRecursion(_InputIter from, _InputIter to) {
//递归的退出条件
if(from == to) {
_output.push_back( std::vector<_Tp>(_first, _last));
return;
}
for(_InputIter j = from; j != to; ++j) {
_InputIter tmp = from;
std::swap(*j, *from);//将当前元素作为排列的第一个元素(与第一个元素交换)
_calcPermutationWithRecursion(++tmp, to);//对剩余的元素进行排列
std::swap(*j, *from);
}
}
private:
_InputIter _first;
_InputIter _last;
std::list< std::vector<_Tp> > &_output;
};
class ObjectPermutationAndCombination
{
public:
template<class _InputIter, class _Tp>
static void permutation(_InputIter first, _InputIter last, std::list< std::vector<_Tp> > &output) {
ObjectPermutation<_InputIter, _Tp> permutation(first, last, output);
permutation.calcPermutationWithRecursion();
}
};
#endif
#include <iostream>
#include <string>
#include <ObjectPermutationAndCombination.hpp>
using namespace std;
template<typename _Tp>
void print( list< std::vector<_Tp> > &output) {
std::cout << "total number:" << output.size() << std::endl;
typename list< std::vector<_Tp> >::iterator lit;
for(lit = output.begin(); lit != output.end(); ++lit) {
typename std::vector<_Tp>::iterator vit;
for(vit = lit->begin(); vit != lit->end(); ++vit) {
cout << *vit;
}
cout << std::endl;
}
}
int main(int argc, char* argv[]) {
char str[] = {'a','b','c','d'};
list< std::vector<char> > output;
ObjectPermutationAndCombination::permutation(str, str + sizeof(str), output);
print(output);
std::cout << "---------" << std::endl;
list<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
list< std::vector<int> > output2;
ObjectPermutationAndCombination::permutation(numbers.begin(), numbers.end(), output2);
print(output2);
return 0;
}
运行结果
total number:24
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
---------
total number:6
123
132
213
231
321
312