[c++]数组全排列
Posted adream307
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[c++]数组全排列相关的知识,希望对你有一定的参考价值。
#include <vector>
#include <functional>
#include <iostream>
using namespace std;
constexpr int empty_val = -1;
void Permutation_List(vector<int> &array, int pos, function<void(const vector<int> &x)> &foo)
if (pos == array.size())
foo(array);
std::vector<bool> used_list(array.size(), false);
for (int i = 0; i < pos; i++)
int v = array[i];
used_list[v] = true;
std::vector<int> remain_list;
remain_list.reserve(array.size());
for (int i = 0; i < used_list.size(); i++)
if (used_list[i] == false) remain_list.push_back(i);
for (auto x : remain_list)
array[pos] = x;
Permutation_List(array, pos + 1, foo);
array[pos] = empty_val;
int main()
vector<int> array(5, -1);
function<void(const vector<int> &x)> foo = [](const vector<int> &x)
for (int v : x)
std::cout << v << " ";
std::cout << std::endl;
;
Permutation_List(array, 0, foo);
程序输出
0 1 2 3 4
0 1 2 4 3
0 1 3 2 4
0 1 3 4 2
0 1 4 2 3
0 1 4 3 2
0 2 1 3 4
0 2 1 4 3
0 2 3 1 4
0 2 3 4 1
0 2 4 1 3
0 2 4 3 1
0 3 1 2 4
0 3 1 4 2
0 3 2 1 4
0 3 2 4 1
0 3 4 1 2
0 3 4 2 1
0 4 1 2 3
0 4 1 3 2
0 4 2 1 3
0 4 2 3 1
0 4 3 1 2
0 4 3 2 1
1 0 2 3 4
1 0 2 4 3
1 0 3 2 4
1 0 3 4 2
1 0 4 2 3
1 0 4 3 2
1 2 0 3 4
1 2 0 4 3
1 2 3 0 4
1 2 3 4 0
1 2 4 0 3
1 2 4 3 0
1 3 0 2 4
1 3 0 4 2
1 3 2 0 4
1 3 2 4 0
1 3 4 0 2
1 3 4 2 0
1 4 0 2 3
1 4 0 3 2
1 4 2 0 3
1 4 2 3 0
1 4 3 0 2
1 4 3 2 0
2 0 1 3 4
2 0 1 4 3
2 0 3 1 4
2 0 3 4 1
2 0 4 1 3
2 0 4 3 1
2 1 0 3 4
2 1 0 4 3
2 1 3 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