选择整数1至n中m个数进行字典序全排列。
输入格式:
输入整数 n,m,0<m<n<10 。
输出格式:
输出所有m个数不重复的全排列,每一行输出一种排列情况,所有的排列情况按字典序输出。最后一行输出全排列的总数。
输入样例:
3 2
输出样例:
注意:除了输出的最后一行,其余每行最后有一个空格
1 2
1 3
2 1
2 3
3 1
3 2
6
#include <iostream>
#include <vector>
using namespace std;
void backtrack(vector<int>& nums, int m, vector<int>& temp, vector<bool>& used, vector<vector<int>>& result) {
if (temp.size() == m) {
result.push_back(temp);
return;
}
for (int i = 0; i < nums.size(); ++i) {
if (used[i]) continue;
temp.push_back(nums[i]);
used[i] = true;
backtrack(nums, m, temp, used, result);
used[i] = false;
temp.pop_back();
}
}
void permutations(int n, int m) {
vector<int> nums;
for (int i = 1; i <= n; ++i) {
nums.push_back(i);
}
vector<vector<int>> result;
vector<int> temp;
vector<bool> used(n, false);
backtrack(nums, m, temp, used, result);
for (auto& permu : result) {
for (int num : permu) {
cout << num << " ";
}
cout << endl;
}
cout << result.size() << endl;
}
int main() {
int n, m;
cin >> n >> m;
permutations(n, m);
return 0;
}
#include <iostream>
#include<list>
using namespace std;
int count =0 ;
void choose(list<int> &re, list<int> l, int m) {
list<int>::iterator it = l.begin();
if (m <= 0) {
for (auto it2 = re.begin();it2 != re.end();++it2) {
cout << *it2 << " ";
}cout << endl;
count++;
return;
}
int temp;
while (it != l.end()) {
temp = *it;
re.push_back(temp);
it = l.erase(it);
choose(re, l, m - 1);
it = l.insert(it, temp);
re.pop_back();
it++;
}
}
int main() {
int m, n;
cin >> n >> m;
list<int> l, re;
for (int i = 1; i <= n; ++i) {
l.push_back(i);
}
list<int>::iterator it = l.begin();
choose(re, l, m);
cout<<count<<endl;
return 0;
}
#include<iostream>
using namespace std;
int a[10],b[10],c[10];
int sum=0;
void func(int b[],int m,int n,int s)
{
if(m==s)
{
for(int i=0;i<s;i++)
{
cout<<c[i]<<" ";
}
cout<<endl;
sum++;
return;
}
else
{
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
a[i]=1;
c[m]=b[i];
func(b,m+1,n,s);
a[i]=0;
}
}
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
{
b[i]=i+1;
a[i]=0;
c[i]=0;
}
func(b,0,n,m);
cout<<sum;
}