排列:
#include
#include
#define ELEMENT std::string
namespace dskit
{
typedef void (*PrintFunc)(const ELEMENT* elements, const size_t size);
class perm
{
public:
perm(size_t size, PrintFunc func_print):m_size(size), m_func_print(func_print) {}
void operator()(ELEMENT* elements, size_t start, size_t end);
private:
void swap(ELEMENT& lhs, ELEMENT& rhs)
{
if(lhs == rhs)
return;
ELEMENT temp = lhs;
lhs = rhs;
rhs = temp;
}
private:
size_t m_size;
PrintFunc m_func_print;
};
void perm::operator()(ELEMENT* elements, size_t start, size_t end)
{
if(start == end)
{
m_func_print(elements, m_size);
}
else
{
for(size_t i = start; i != end; ++i)
{
swap(elements[i], elements[start]);
operator()(elements, start + 1, end);
swap(elements[i], elements[start]);
}
}
}
}
void print(const ELEMENT* elements, const size_t size)
{
for(size_t i = 0; i != size; ++i)
{
std::cout << elements[i] << '/t';
}
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
ELEMENT array[] = {"d", "da", "af", "5", "8"};
dskit::perm(sizeof(array) / sizeof(ELEMENT), print)(array, 0, sizeof(array) / sizeof(ELEMENT));
}
组合:
#ifndef __COMBINATION_H__
#define __COMBINATION_H__
#include
typedef int ELEMENTTYPE;
#define MAXELEMENT 100
void combination(std::ostream& out, const ELEMENTTYPE* src, size_t n_set);
void combination_sorted(std::ostream& out, const ELEMENTTYPE* src, size_t n_set, size_t n_subset, size_t start_pos = 0);
void combination_sorted(std::ostream& out, const ELEMENTTYPE* src, size_t n_set);
#endif
#include
#include
#include"combination.h"
ELEMENTTYPE res[MAXELEMENT];
void combination(std::ostream& out, const ELEMENTTYPE* src, size_t n_set)
{
if(n_set > 63)
return;
for(size_t i = 0; i < (1 << n_set); ++i)
{
std::bitset bs(i);
for(size_t j = 0; j < n_set; ++j)
if(bs[j]) ;
out << src[j] << "/t";
out << std::endl;
}
}
void combination_sorted(std::ostream& out, const ELEMENTTYPE* src, size_t n_set, size_t n_subset, size_t start_pos)
{
static size_t dep = 0;
if(0 == n_subset)
{
for(size_t index = 0; index < dep; ++index)
out << res[index] << "/t";
out << std::endl;
}
else
{
for(size_t i = start_pos; i <= n_set - n_subset; ++i)
{
res[dep] = src[i];
++dep;
combination_sorted(out, src, n_set, n_subset - 1, i + 1);
--dep;
}
}
}
void combination_sorted(std::ostream& out, const ELEMENTTYPE* src, size_t n_set)
{
for(size_t i = 0; i != n_set + 1; ++i)
combination_sorted(out, src, n_set, i, 0);
}