一、n个数全排列
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int flag[200], a[200];
int n = 5;
void dfs(int step)
{
if (step - 1 == m)
{
for (int i = 0; i < step; i++)
{
cout << a[i];
cout << (i == m ? "\n" : " ");
}
return;
}
for (int i = 1; i <= m; i++)
{
if (flag[i] == 0)
{
a[step] = i;
flag[i] = 1;
dfs(step + 1);
flag[i] = 0;
}
}
}
int main()
{
dfs(0);
}
二、n个数中选m个数递增排列
#include <iostream>
using namespace std;
int num[] = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14};
int n = 12; //总数
int m = 5; //需要选择的个数
int a[20];
void dfs(int pos, int step)
{
if (step == m)
{
for (int i = 0; i < step; i++)
cout << a[i] << ' ';
cout << endl;
return;
}
if (n - pos < m - step) //如果剩下的数的个数小于还要选的个数
return;
for (int i = pos; i < n; i++)
{
a[step] = num[i];
dfs(i + 1, step + 1);
}
}
int main()
{
dfs(0, 0);
system("pause");
return 0;
}