题目描述
设有 n 个整数的集合 {1,2,3,…,n},从中取出任意 r 个数进行排列(0 < r < n < 10),编程输出所有的排列方案。请按照字典序输出。
输入描述 一行两个整数 n 和 r,之间用一个空格隔开。
输出描述 所有排列方案,每一行r个整数,每一种方案用换行分隔。 最后一行输出方案总数,格式见样例。 输入 4 2 输出 12 13 14 21 23 24 31 32 34 41 42 43 total=12
#include<bits/stdc++.h>
using namespace std;
int n, r, ans = 0, total = 12;
int book[1005];
int a[1005];
void dfs(int cur){
if(cur == r){
for(int i = 0; i < cur; i++){
cout << a[i];
}
cout << endl;
ans++;
return;
}
for(int i = 1; i <= n; i++){
if(!book[i]){
book[i] = 1;
a[cur] = i;
dfs(cur + 1);
book[i] = 0;
}
}
}
int main() {
cin >> n >> r;
dfs(0);
cout <<"total = " << ans << endl;
return 0;
}
但是全错