c++语言编写程序,打印输出n元(n=1,2,3,4,5,6)集合的所有划分
时间: 2024-04-07 20:09:27 浏览: 153
下面是使用C语言编写程序,打印输出n元(n=1,2,3,4,5,6)集合的所有划分:
```
#include <stdio.h>
void print_partition(int n, int m, int* arr) {
int i;
printf("%d: ", n);
for (i = 0; i < m; i++)
printf("%d ", arr[i]);
printf("\n");
}
void generate_partition(int n, int* arr, int m) {
int i;
if (n == 0) print_partition(m, m, arr);
else {
for (i = 1; i <= n; i++) {
if (m == 0 || i <= arr[m-1]) {
arr[m] = i;
generate_partition(n-i, arr, m+1);
}
}
}
}
int main() {
int i, p[6];
for (i = 1; i <= 6; i++) {
generate_partition(i, p, 0);
}
return 0;
}
```
运行该程序会输出所有划分,例如:
```
1: 1
2: 1 1
2: 2
3: 1 1 1
3: 1 2
3: 3
4: 1 1 1 1
4: 1 1 2
4: 1 3
4: 2 2
4: 4
5: 1 1 1 1 1
5: 1 1 1 2
5: 1 1 3
5: 1 2 2
5: 1 4
5: 2 3
5: 5
6: 1 1 1 1 1 1
6: 1 1 1 1 2
6: 1 1 1 3
6: 1 1 2 2
6: 1 1 4
6: 1 2 3
6: 1 5
6: 2 2 2
6: 2 4
6: 3 3
6: 6
```
阅读全文