# STL：从N个元素中取出M个的所有组合

``````#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

const size_t M = 3;

void premutate(std::vector<int> &v, int data[], int num = 0)
{

if (num == M)
{//output
copy(data, data + num, ostream_iterator<int>(cout, " "));
cout << endl;
return;
}
else
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
//我们注意到,对有序的数排列的时候,排列后面的数都比前面的大
//我们利用这个特性,快速的判断一个数是否已经在排列当中了
if ( num != 0 && data[num - 1] >= *it )
{
continue;
}
else
{
data[num] = *it;
premutate(v, data, num + 1);
}
}
}
}

int main(int argc, char* argv[])
{
int  elements[] = {1,2,3,4,5};
const size_t N = sizeof(elements) / sizeof(elements[0]);
std::vector<int> selectors(elements, elements + N);
int data[N] = {0};

sort(selectors.begin(), selectors.end());
premutate(selectors, data);
return 0;
}
``````

``````#include <assert.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
int values[] = { 1, 2, 3, 4, 5, 6, 7 };
int elements[] = { 1, 1, 1, 0, 0, 0, 0 };
const size_t N = sizeof(elements)/sizeof(elements[0]);
assert(N == sizeof(values)/sizeof(values[0]));
std::vector<int> selectors(elements, elements + N);

int count = 0;
do
{
std::cout << ++count << ": ";
for (size_t i = 0; i < selectors.size(); ++i)
{
if (selectors[i])
{
std::cout << values[i] << ", ";
}
}
std::cout << std::endl;
} while (prev_permutation(selectors.begin(), selectors.end()));
}
``````

/
Published under (CC) BY-NC-SA in categories 算法  tagged with STL  algorithm  排列