Вывести все последовательности длины n, состоящие из чисел от 1 до m. Каждое число может встречаться в последовательности
несколько раз или не встречаться совсем.
#include "fstream"
#include "vector"
using namespace std;
ifstream cin("input.txt");
ofstream cout("output.txt");
int n, m;
vector a;
void out()
{
for (int i = 0; i < n; i++)
{
if (i)
cout << " ";
cout << a[i];
}
cout << endl;
}
void rec(int idx)
{
if (idx == n)
{
out();
return;
}
for (int i = 1; i <= m; i++)
{
a[idx] = i;
rec(idx + 1);
}
}
int main()
{
cin >> n >> m;
a = vector(n);
rec(0);
return 0;
}
Генерация перестановок
Вывести все последовательности чисел от 1 до n, в которых каждое число встречается ровно один раз. Такие последовательности
называются перестановками.
#include "fstream"
#include "vector"
using namespace std;
ifstream cin("input.txt");
ofstream cout("output.txt");
int n, m;
vector a;
vector used;
void out()
{
for (int i = 0; i < n; i++)
{
if (i)
cout << " ";
cout << a[i];
}
cout << endl;
}
void rec(int idx)
{
if (idx == n)
{
out();
return;
}
for (int i = 1; i <= m; i++)
{
if (used[i]) continue;
a[idx] = i;
used[i] = true;
rec(idx + 1);
used[i] = false;
}
}
int main()
{
cin >> n >> m;
a = vector(n);
used = vector(n + 1, false);
rec(0);
return 0;
}
Ссылки по теме
- .