法一:dfs
#include <iostream>
#include<iomanip>
using namespace std;
int num[100];
void dfs(int n,int r,int k,int num[]) {
if (k > r) {
for (int i = 1; i <= r; i++) {
cout << setw(3) << num[i];
}
cout << endl;
return;
}
for (int i = num[k - 1] + 1; i <= n; i++) {
num[k] = i;
dfs(n,r,k + 1,num);
}
}
int main() {
int n, r;
cin >> n >> r;
dfs(n,r,1,num);
}
法二:STL next_permutation
利用自动生成的全排列来输出(注意必须按照字典序)
#include <iostream>
#include <algorithm>
#include <vector>
#include<iomanip>
using namespace std;
int main() {
int n, r;
cin >> n >> r;
vector<int>num;
num.resize(n, 1);
for (int i = 0; i < r; i++) {
num[i] = 0;
}
do{
for (int i = 0; i < n; i++) {
if (num[i] == 0) {
cout << setw(3) << i + 1;
}
}
cout << endl;
}while(next_permutation(num.begin(), num.end()));
return 0;
}