36 lines
800 B
C++
36 lines
800 B
C++
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
void PrintPartitions(int n, int max, int* partition, int index) {
|
|
// 基本情況
|
|
if (n == 0) {
|
|
// 當 n 為 0 時,表示找到一種分割方式,輸出結果
|
|
for (int i = 0; i < index; i++) {
|
|
printf("%d", partition[i]);
|
|
if (i < index - 1) {
|
|
printf(" ");
|
|
}
|
|
}
|
|
printf("\n");
|
|
return;
|
|
}
|
|
|
|
// 遞迴情況
|
|
for (int i = (max > n) ? n : max; i >= 1; i--) {
|
|
partition[index] = i;
|
|
PrintPartitions(n - i, i, partition, index + 1);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
int num;
|
|
printf("輸入欲分割的正整數 ==> ");
|
|
scanf("%d", &num);
|
|
|
|
int* partition = (int*) calloc(num, sizeof(int));
|
|
PrintPartitions(num, num, partition, 0);
|
|
|
|
free(partition);
|
|
return 0;
|
|
}
|