指数型枚举
#include <iostream>
using namespace std;
int n, num[15];
void print(int cnt) {
cout << num[1];
for (int i = 2; i <= cnt; i++) {
cout << " " << num[i];
}
cout << endl;
}
//从第几个数字开始,更改第几位的数字
void func(int start, int number) {
for (int i = start; i <= n; i++) {
num[number] = i;
print(number);
func(i + 1, number + 1);
}
}
int main() {
cin >> n;
func(1, 1);
return 0;
}
结果
输入: 4
1
1 2
1 2 3
1 2 3 4
1 2 4
1 3
1 3 4
1 4
2
2 3
2 3 4
2 4
3
3 4
4
组合型枚举
#include <iostream>
using namespace std;
int n, m, num[15];
void print(int cnt) {
cout << num[1];
for (int i = 2; i <= cnt; i++) {
cout << " " << num[i];
}
cout << endl;
}
//从第几个数字开始,更改第几位的数字
void func(int start, int number) {
if (number == m + 1) {
print(m);
return;
}
for (int i = start; i <= n; i++) {
num[number] = i;
func(i + 1, number + 1);
}
}
int main() {
cin >> n >> m;
func(1, 1);
return 0;
}
结果
输入: 5 3
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
排列型枚举
#include <iostream>
using namespace std;
int n, m, num[15], mark[15];
void print(int cnt) {
cout << num[1];
for (int i = 2; i <= cnt; i++) {
cout << " " << num[i];
}
cout << endl;
}
//更改第几位的数字
void func(int number) {
if (number == m + 1) {
print(m);
return;
}
for (int i = 1; i <= n; i++) {
if (mark[i] == 1) continue;
num[number] = i;
mark[i] = 1;
func(number + 1);
mark[i] = 0;
}
}
int main() {
cin >> n >> m;
func(1);
return 0;
}
结果
输入: 3 3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
(总结)递归二要素:
- 递归边界
- 递归函数的意义!!!